调优随机森林的超参数

Python 树模型机器学习

Elie Kawerk

Data Scientist

随机森林的超参数

  • CART 超参数

  • 基学习器数量

  • 自助采样(bootstrap)

  • ……

Python 树模型机器学习

调优成本高

超参数调优:

  • 计算开销大,

  • 有时仅带来轻微提升,

权衡调优对整个项目的影响。

Python 树模型机器学习

查看 sklearn 中的 RF 超参数

# 导入 RandomForestRegressor 
from sklearn.ensemble import RandomForestRegressor

# 设定随机种子,保证可复现
SEED = 1

# 实例化随机森林回归器 'rf' 
rf = RandomForestRegressor(random_state= SEED)

Python 树模型机器学习
# 查看 rf 的超参数
rf.get_params()
{'bootstrap': True,
 'criterion': 'mse',
 'max_depth': None,
 'max_features': 'auto',
 '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,
 'n_estimators': 10,
 'n_jobs': -1,
 'oob_score': False,
 'random_state': 1,
 'verbose': 0,
 'warm_start': False}
Python 树模型机器学习
# 基本导入
from sklearn.metrics import mean_squared_error as MSE
from sklearn.model_selection import GridSearchCV

# 定义超参数网格 'params_rf' params_rf = { 'n_estimators': [300, 400, 500], 'max_depth': [4, 6, 8], 'min_samples_leaf': [0.1, 0.2], 'max_features': ['log2', 'sqrt'] }
# 实例化 'grid_rf' grid_rf = GridSearchCV(estimator=rf, param_grid=params_rf, cv=3, scoring='neg_mean_squared_error', verbose=1, n_jobs=-1)
Python 树模型机器学习

搜索最佳超参数

# 在训练集上拟合 'grid_rf'
grid_rf.fit(X_train, y_train)
对每个 36 个候选进行 3 折拟合,共 108 次拟合
[Parallel(n_jobs=-1)]: Done  42 tasks      | elapsed:   10.0s
[Parallel(n_jobs=-1)]: Done 108 out of 108 | elapsed:   24.3s finished
RandomForestRegressor(bootstrap=True, criterion='mse', max_depth=4,
           max_features='log2', max_leaf_nodes=None,
           min_impurity_decrease=0.0, min_impurity_split=None,
           min_samples_leaf=0.1, min_samples_split=2,
           min_weight_fraction_leaf=0.0, n_estimators=400, n_jobs=1,
           oob_score=False, random_state=1, verbose=0, warm_start=False)
Python 树模型机器学习

提取最佳超参数

# 从 'grid_rf' 中提取最佳超参数
best_hyperparams = grid_rf.best_params_

print('最佳超参数:\n', best_hyperparams)
最佳超参数:
        {'max_depth': 4,
         'max_features': 'log2', 
         'min_samples_leaf': 0.1,
         'n_estimators': 400}
Python 树模型机器学习

评估最佳模型性能

# 从 'grid_rf' 中提取最佳模型
best_model = grid_rf.best_estimator_
# 预测测试集标签
y_pred = best_model.predict(X_test)
# 评估测试集 RMSE
rmse_test = MSE(y_test, y_pred)**(1/2)
# 打印测试集 RMSE
print('rf 测试集 RMSE: {:.2f}'.format(rmse_test))
rf 测试集 RMSE: 3.89
Python 树模型机器学习

Passons à la pratique !

Python 树模型机器学习

Preparing Video For Download...