[Python] Catboost Bayesian Optimization

2019. 6. 1. 18:22ML(머신러닝)/Optimization

728x90

최근에 Tree based 모델을 좀 보고 있는데, Python에서 categorical 변수를 One-hot을 하지 않고 하는 알고리즘은

현재, lightgbm과 catboost인 것 같다.

 

개인적으로 원핫을 안 좋아해서 인지, xgboost는 별로 하기가 싫다.

물론 tree-based model이라서 다차원으로 갔을 때의 고민이 좀 없겠지만,

현재 데이터중에 날짜 데이터도 있는데.. 이것을 onehot 하면 너무 Sparse하지 않겠는가...............

 

그래서 나는 여기선 catboost를 parameter tuning을 해보려고 한다.

 

https://data-newbie.tistory.com/131   이전에 간략하게 논문리뷰를 해봤다.

 

CatBoost란? unbiased boosting with categorical features - 1

논문 및 Document https://arxiv.org/abs/1706.09516 https://catboost.ai/docs/concepts/python-reference_catboostclassifier_fit.html 현재 Xgboost , lightgbm , gbm 계열인 Gradient Boosting 은 weak learne..

data-newbie.tistory.com

 

Catboost는 Parameter를 대충한다해도, 잘 나온다고 하지만, 

그래도 역시 조금이라도 올리기 위해서는 Parameter tuning은 필요하고,

나는 그 중에서도 너무 랜덤 하게랑 grid별로 하고 싶지 않아서 

 

Bayesian Optimization으로 해결하고자하고 코드를 구현했다.

지금은 인터넷에서 찾아봐도 없어서 해보긴 했는데, 음 없는 이유는 굳이 그럴 필요가 없어서 안 하는 건가....ㅠ

 

def catboost_eval(bagging_temperature ,
                  depth , 
                  learning_rate ,
                  min_data_in_leaf , 
                  max_leaves , 
                  l2_leaf_reg , 
                  border_count):
    n_splits=5
    skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=RANDOM_STATE)
    f1 = []
    predict = None
    params = {}
    params['iterations'] = 1000
    params['custom_loss'] = 'TotalF1'
    params['eval_metric'] = 'TotalF1'
    params['random_seed'] = 1234
    params['learning_rate'] = learning_rate
    params['min_data_in_leaf'] = int(round(min_data_in_leaf))
    params['depth'] = int(round(depth))
    #params['max_leaves'] = int(round(max_leaves))
    #params['l2_leaf_reg'] = int(round(l2_leaf_reg))
    params['border_count'] = int(round(border_count))
    params['bagging_temperature'] = int(round(bagging_temperature))
    X , y = catX_train.values , caty_train
    for tr_ind, val_ind in skf.split(X , y):
        X_train = X[tr_ind]
        y_train = y[tr_ind]
        X_valid = X[val_ind]
        y_valid = y[val_ind]
        ## https://catboost.ai/docs/concepts/python-reference_catboost_eval-metrics.html
        clf = CatBoostClassifier(**params , 
                                 task_type = "GPU" , 
                                 leaf_estimation_iterations = 10,
                                 use_best_model=True,
                                 od_type="Iter",
                                 logging_level='Silent',
                                )
        clf.fit(X_train, 
                y_train,
                cat_features=cat_features,
                eval_set=(X_valid, y_valid),
                verbose = False ,
        )
        
        y_pred = clf.predict(X_valid)
        
        f1_value = f1_score(y_valid.astype(int) ,
                            y_pred.astype(int)  ,
                            average='weighted')
        f1.append(f1_value)
    return sum(f1)/n_splits

## min_data_in_leaf , max_leaves , 추가 하니 먼가 잘 안됨.
catBO = BayesianOptimization(catboost_eval,
                             {'bagging_temperature': (0, 1000),
                              'depth': (5, 8.99) ,
                              "learning_rate" : (0.001,0.1) , 
                              "min_data_in_leaf" : (1,6) , 
                              'max_leaves' : (200,200)  ,
                              'l2_leaf_reg': (100, 100)  ,
                              'border_count': (5, 255) ,
                             },
                             random_state=0)
init_round=5
opt_round = 10
catBO.maximize(init_points=init_round, n_iter=opt_round)




### 변수 중요도 시각화
import seaborn as sns
sns.set(rc={'figure.figsize':(11.7,8.27)})
cat_feature_imp = pd.DataFrame([CatBoost.feature_names_ , CatBoost.feature_importances_]).T
cat_feature_imp.columns = ["feature","varimp"]
cat_feature_imp = cat_feature_imp.sort_values(by="varimp", ascending = False)
sns.barplot(y="feature", x="varimp",data = cat_feature_imp, )
plt.show()

 

## 2019.08.02 

누군가 미디엄에 부스팅 기반으로 올려줬다.

 

https://towardsdatascience.com/an-example-of-hyperparameter-optimization-on-xgboost-lightgbm-and-catboost-using-hyperopt-12bc41a271e

 

An Example of Hyperparameter Optimization on XGBoost, LightGBM and CatBoost using Hyperopt

Bonus: Hyperopt-Sklearn

towardsdatascience.com

 

728x90