调优 CART 的超参数

Python 树模型机器学习

Elie Kawerk

Data Scientist

超参数

机器学习模型:

  • 参数:从数据中学习得到

    • CART 示例:节点分割点、节点分割特征等
  • 超参数:非从数据学习,训练前设定

    • CART 示例:max_depthmin_samples_leaf、分裂准则等
Python 树模型机器学习

什么是超参数调优?

  • 问题:为学习算法寻找一组最优超参数。

  • 解决方案:找到使模型最优的一组超参数。

  • 最优模型:得到最优评分。

  • 评分:在 sklearn 中,分类默认为 accuracy,回归为 $R^2$。

  • 使用交叉验证估计泛化性能。

Python 树模型机器学习

为何要调优超参数?

  • sklearn 中,模型默认超参数并非对所有问题都最优。

  • 应调优超参数以获得最佳模型性能。

Python 树模型机器学习

超参数调优方法

  • 网格搜索

  • 随机搜索

  • 贝叶斯优化

  • 遗传算法

  • ……

Python 树模型机器学习

网格搜索交叉验证

  • 手动设定离散超参数取值网格。

  • 设定评估指标。

  • 穷举搜索整个网格。

  • 对每组超参数,评估其模型的 CV 分数。

  • 最优超参数为取得最佳 CV 分数的那组。

Python 树模型机器学习

网格搜索交叉验证:示例

  • 超参数网格:
    • max_depth = {2,3,4},
    • min_samples_leaf = {0.05, 0.1}
  • 超参数空间 = { (2,0.05) , (2,0.1) , (3,0.05), ... }
  • 交叉验证分数 = { $score_{(2,0.05)}$ , ... }
  • 最优超参数 = 对应最佳 CV 分数的一组超参数。
Python 树模型机器学习

查看 sklearn 中 CART 的超参数

# Import DecisionTreeClassifier
from sklearn.tree import DecisionTreeClassifier

# Set seed to 1 for reproducibility
SEED = 1

# Instantiate a DecisionTreeClassifier 'dt'
dt = DecisionTreeClassifier(random_state=SEED)

Python 树模型机器学习

查看 sklearn 中 CART 的超参数

# Print out 'dt's hyperparameters
print(dt.get_params())
        {'class_weight': None,
         'criterion': 'gini',
         'max_depth': None,
         'max_features': None,
         'max_leaf_nodes': None,
         'min_impurity_decrease': 0.0,
         'min_impurity_split': None,
         'min_samples_leaf': 1,
         'min_samples_split': 2,
         'min_weight_fraction_leaf': 0.0,
         'presort': False,
         'random_state': 1,
         'splitter': 'best'}
Python 树模型机器学习
# Import GridSearchCV
from sklearn.model_selection import GridSearchCV

# Define the grid of hyperparameters 'params_dt' params_dt = { 'max_depth': [3, 4,5, 6], 'min_samples_leaf': [0.04, 0.06, 0.08], 'max_features': [0.2, 0.4,0.6, 0.8] }
# Instantiate a 10-fold CV grid search object 'grid_dt' grid_dt = GridSearchCV(estimator=dt, param_grid=params_dt, scoring='accuracy', cv=10, n_jobs=-1)
# Fit 'grid_dt' to the training data grid_dt.fit(X_train, y_train)
Python 树模型机器学习

提取最优超参数

# Extract best hyperparameters from 'grid_dt'
best_hyperparams = grid_dt.best_params_
print('Best hyerparameters:\n', best_hyperparams)
Best hyerparameters:
  {'max_depth': 3, 'max_features': 0.4, 'min_samples_leaf': 0.06}
# Extract best CV score from 'grid_dt'
best_CV_score = grid_dt.best_score_
print('Best CV accuracy'.format(best_CV_score))
Best CV accuracy: 0.938
Python 树模型机器学习

提取最佳估计器

# Extract best model from 'grid_dt'
best_model = grid_dt.best_estimator_

# Evaluate test set accuracy test_acc = best_model.score(X_test,y_test) # Print test set accuracy print("Test set accuracy of best model: {:.3f}".format(test_acc))
Test set accuracy of best model: 0.947
Python 树模型机器学习

Passons à la pratique !

Python 树模型机器学习

Preparing Video For Download...