Data & ML & AI/Pandas & Scikit-Learn
10. Grid Search: 머신러닝 모델 하이퍼파라미터 튜닝, 최적화 손쉽게 하기(feat. scikit learn)
뇌님
2023. 3. 30. 00:37
반응형
하이퍼파라미터를 하나하나 바꿔가며 모델을 테스트 하는 것은 참 귀찮은 일입니다.
그래서 scikit learn은 그리드탐색(Grid Search)과 랜덤탐색(Random Search)를 지원합니다.
Grid Search
그리드 탐색은 주어진 하이퍼파라미터들 중, 최적의 조합을 찾아내는 기법입니다.
- 사용자(분석자)가 미리 하이퍼파라미터 세트들을 정의함
- 모든 경우의 수로 하이퍼파라미터 조합을 생성, 모든 경우에 대해 머신러닝을 수행
- 가장 우수한 성능을 가진 하이퍼파라미터 조합이 최종적으로 선택됨
sklearn의 toy data인 iris data를 활용한 예시 코드입니다.
from sklearn.datasets import load_iris
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
# Load the iris dataset
iris = load_iris()
# Define the parameter grid
param_grid = {'C': [0.1, 1, 10, 100],
'gamma': [0.1, 1, 10, 100],
'kernel': ['linear', 'rbf']}
# Create an instance of the SVM classifier
svm = SVC()
# Create an instance of the GridSearchCV class
grid_search = GridSearchCV(svm, param_grid, cv=5)
# Fit the grid search to the data
best_model = grid_search.fit(iris.data, iris.target)
# Print the best hyperparameters
print(best_model.best_params_)
# {'C': 1, 'gamma': 0.1, 'kernel': 'linear'}
C = 1, gamma=0.1, kernel='linear'로 설정하는 것이 가장 좋다고 하는군요.
Grid Search의 장단점
장점
- 주어진 조건에 대한 모든 조합을 놓치지 않고 평가할 수 있다.
- 구현하기 매우매우 쉽다(라이브러리의 도움을 쉽게 받을 수 있다)
- 최적의 조합을 알려주므로 손쉽게 모델을 학습, 재학습 시킬 수 있다.
단점
- 모든 경우의 수를 다 평가하기 때문에 계산비용이 많이 든다.
- 미리 정의한 하이퍼파라미터 세트들 만으로 탐색한다.
그 외에 존재할 수 있는 global optimum을 놓칠 수 있다.
Random Search
랜덤탐색은 크게 두가지 의미가 있습니다.
- 하이퍼파라미터 세트를 무작위로 생성해서 탐색(search)한다.
- 주어진 하이퍼파라미터 세트중, 무작위 조합 몇개만 선출해서 탐색한다.
1: 이 글 처음에 있는 그림의 내용입니다.
2: Grid Search가 모든 조합을 다 탐색하기 때문에 오래 걸린다면, 몇개의 조합만 탐색해서 시간을 줄이겠다는 겁니다.
scikit learn이 제공하는 random search는 2번에 대한 코드입니다.
from sklearn.datasets import load_iris
from sklearn.model_selection import RandomizedSearchCV
from sklearn.svm import SVC
import random
# Load the iris dataset
iris = load_iris()
# Define the parameter distributions
param_distribs = {'C': [0.1, 1, 10, 100],
'gamma': [0.1, 1, 10, 100],
'kernel': ['linear', 'rbf']}
# Create an instance of the SVM classifier
svm = SVC()
# Create an instance of the RandomizedSearchCV class
# 이부분만 다릅니다
random_search = RandomizedSearchCV(svm, param_distribs, cv=5, n_iter=10)
# Fit the grid search to the data
best_model = random_search.fit(iris.data, iris.target)
# Print the best hyperparameters
print(best_model.best_params_)
# {'kernel': 'rbf', 'gamma': 0.1, 'C': 1}
원래의 Grid Search라면 C(4개) X gamma(4개) X kernel(2개) = 조합 32개 를 모두 탐색했겠지만,
위 코드에서의 random search는 그 중 n_iter=10개의 조합 만을 무작위로 탐색하고 끝내버립니다.
반응형