프로그래밍/머신러닝&딥러닝

[machine learning] 하이퍼파라미터 최적화(Optuna)

지원지원 2021. 2. 16. 23:07

최적화 된 파라미터를 찾기 위해서 하이퍼파라미터 값을 조정하면서, 가장 좋은 결과가 나올 때까지 돌려봐야한다

이거 너무 번거롭고 귀찮고 시간도 오래 걸릴 때가 많다. 

 

Optuna : 하이퍼파라미터 최적화

: 하이퍼 파라미터 최적화를 도와주는 프레임워크

파라미터의 범위나 리스트를 지정해주면, trail마다 파라미터를 변경하면서 최적의 파라미터를 지정해준다.

optuna는 study 개체를 기반으로 한다. 이 개체에는 필요한 파라미터 공간에 대한 정보와 sampler 방법과 pruning에 대한 정보가 포함되어 있다. 

 

<하이퍼파라미터 범위나 리스트 설정하는 방법>

from sklearn.model_selection import train_test_split
from sklearn.metrics import log_loss
import optuna

#정의
def objective(trial, data=data, target=target):
	
    x_train, x_val, y_train, y_val = train_test_split(data, target, test_size=0.2, random_state=1)
    param = {
    	'objective':'multiclass',
        'metric': 'multi_logloss', 
        'random_state': 71,
        'n_estimators': 200,
        'reg_alpha': trial.suggest_loguniform('reg_alpha', 1e-3, 10.0),
        'reg_lambda': trial.suggest_loguniform('reg_lambda', 1e-3, 10.0),
        'colsample_bytree': trial.suggest_categorical('colsample_bytree', [0.6,0.7,0.8,0.9,1.0]),
        'subsample': trial.suggest_categorical('subsample',[0.6,0.7,0.8,0.9,1.0]),
        'learning_rate': trial.suggest_categorical('learning_rate',[0.002,0.007,0.01,0.014,0.017,0.02]),
        'max_depth': trial.suggest_categorical('max_depth', [15,25,100]),
        'num_leaves' : trial.suggest_int('num_leaves',8, 20),
        'min_child_samples': trial.suggest_int('min_child_samples', 1, 31)
    }
    
    model = LGBMClassifier(**param)  
    model.fit(X_tr,y_tr,eval_set=[(X_val,y_val)],early_stopping_rounds=25,verbose=False)

    preds = model.predict_proba(X_val)
    score = log_loss(y_val, preds)
    return score


#학습
study=optuna.create_study(direction='minimize') #study 객체 생성
study.optimize(objective,n_trials=10)
print('Number of finished trials:',len(study.trials))
print('Best trial:',study.best_trial.params)

 trail 함수 참고 링크 

: optuna.readthedocs.io/en/latest/reference/generated/optuna.trial.Trial.html#optuna.trial.Trial

suggest_loguniform - float values

suggest_uniform - float values

suggest_discrete_uniform - float values with intervals

suggest_int - integer values

suggest_categorical - categorical values from a list


 

그냥 스터디 하다가 끄적 ~ ~ ~ ~ 

 

출처 : 

sincerechloe.tistory.com/68

 

Optuna를 이용한 hyper parameter optimization

이 포스트는 아래 원문의 내용을 참고하여 번역 및 수정한 것이다. 원문을 보고 싶으면 아래 링크에서 확인할 수 있다. 원문: A 5 min guide to hyper-parameter optimization with Optuna In this post, we will..

sincerechloe.tistory.com

github.com/Sejong-Kaggle-Challengers/MAIN/issues/21