그녀의 일

모델의 최적의 하이퍼 파라미터 찾기 | Hyperparameter tuning - GridSearchCV, RandomizedSearchCV

뻔짓 2023. 3. 9. 11:34
728x90
반응형

 

1. GridSearchCV()

: 시도해 볼 하이퍼파라미터들을 지정하면, 모든 조합에 대해 교차검증 후 가장 좋은 성능을 내는 하이퍼파라미터 조합을 찾음.

단, 하이퍼파라미터 값들이 많아지면 시간이 오래 걸린다는 단점이 있음.

 

파라미터 설명

​주요 매개변수
> estimator : 모델 객체 지정
> param_grid : 하이퍼파라미터 목록을 dictionary 로 전달
> scoring : 평가 지표
> cv : 교차검증 시 fold 개수
> n_jobs : 사용할 CPU 코어 개수 (1: 기본값, -1: 모든 코어 다 사용)

메소드
> fit(X, y) : 학습
> predict(X) : 제일 좋은 성능을 낸 모델로 예측
> predict_proba(X) : 제일 좋은 성능을 낸 모델로 predict_proba() 호출

결과 조회 변수
> cv_results_ : 파라미터 조합별 결과 조회
> best_params_ : 가장 좋은 성능을 낸 parameter 조합 조회
> best_estimator_ : 가장 좋은 성능을 낸 모델 반환

 

예시

 
penalty = ['l1', 'l2']
C = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000]
class_weight = [{1:0.5, 0:0.5}, {1:0.4, 0:0.6}, {1:0.6, 0:0.4}, {1:0.7, 0:0.3}]
solver = ['liblinear', 'saga']

param_grid = dict(penalty=penalty,
                  C=C,
                  class_weight=class_weight,
                  solver=solver)

grid = GridSearchCV(estimator=logistic, param_grid=param_grid, scoring='roc_auc', verbose=1, n_jobs=-1)
grid_result = grid.fit(X_train, y_train)

print('Best Score: ', grid_result.best_score_)
print('Best Params: ', grid_result.best_params_)
Best Score:  0.7899186582809224
Best Params:  {'C': 1, 'class_weight': {1: 0.6, 0: 0.4}, 'penalty': 'l1', 'solver': 'liblinear'}

GridSearch로 찾은 하이퍼파라미터 조합으로 LogisticRegression (estimator) 적용

logistic = linear_model.LogisticRegression(C=1, class_weight={1:0.6, 0:0.4}, penalty='l1', solver='liblinear')
get_cv_scores(logistic)
 

 

3. RandomizedSearchCV()

: GridSearch 와 동일한 방식으로 사용하지만 모든 조합을 다 시도하지는 않고, 각 반복마다 임의의 값만 대입해 지정한 횟수만큼 평가함.

 

파라미터 설명

주요 매개변수
> estimator : 모델 객체 지정
> param_distributions : 하이퍼파라미터 목록을 dictionary 로 전달
> n_iter : 파라미터 검색 횟수 (default = 10)
> scoring : 평가 지표
> cv : 교차검증 시 fold 개수
> n_jobs : 사용할 CPU 코어 개수 (1: 기본값, -1: 모든 코어 다 사용)

메소드
> fit(X, y) : 학습
> predict(X) : 제일 좋은 성능을 낸 모델로 예측
> predict_proba(X) : 제일 좋은 성능을 낸 모델로 predict_proba() 호출

결과 조회 변수
> cv_results_ : 파라미터 조합별 결과 조회
> best_params_ : 가장 좋은 성능을 낸 parameter 조합 조회
> best_estimator_ : 가장 좋은 성능을 낸 모델 반환

 

예시

loss = ['hinge', 'log', 'modified_huber', 'squared_hinge', 'perceptron']
penalty = ['l1', 'l2', 'elasticnet']
alpha = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000]
learning_rate = ['constant', 'optimal', 'invscaling', 'adaptive']
class_weight = [{1:0.5, 0:0.5}, {1:0.4, 0:0.6}, {1:0.6, 0:0.4}, {1:0.7, 0:0.3}]
eta0 = [1, 10, 100]

param_distributions = dict(loss=loss,
                           penalty=penalty,
                           alpha=alpha,
                           learning_rate=learning_rate,
                           class_weight=class_weight,
                           eta0=eta0)

random = RandomizedSearchCV(estimator=sgd, param_distributions=param_distributions, scoring='roc_auc', verbose=1, n_jobs=-1, n_iter=1000)
random_result = random.fit(X_train, y_train)

print('Best Score: ', random_result.best_score_)
print('Best Params: ', random_result.best_params_)
Best Score:  0.7980969951083158
Best Params:  {'penalty': 'elasticnet', 'loss': 'log', 'learning_rate': 'invscaling', 'eta0': 1, 'class_weight': {1: 0.7, 0: 0.3}, 'alpha': 0.1}
sgd = linear_model.SGDClassifier(alpha=0.1,
                                 class_weight={1:0.7, 0:0.3},
                                 eta0=100,
                                 learning_rate='optimal',
                                 loss='log',
                                 penalty='elasticnet')
get_cv_scores(sgd)
728x90
반응형