Python 树模型机器学习
Elie Kawerk
Data Scientist
机器学习模型:
参数:从数据中学习得到
超参数:非从数据学习,训练前设定
max_depth、min_samples_leaf、分裂准则等问题:为学习算法寻找一组最优超参数。
解决方案:找到使模型最优的一组超参数。
最优模型:得到最优评分。
评分:在 sklearn 中,分类默认为 accuracy,回归为 $R^2$。
使用交叉验证估计泛化性能。
在 sklearn 中,模型默认超参数并非对所有问题都最优。
应调优超参数以获得最佳模型性能。
网格搜索
随机搜索
贝叶斯优化
遗传算法
……
手动设定离散超参数取值网格。
设定评估指标。
穷举搜索整个网格。
对每组超参数,评估其模型的 CV 分数。
最优超参数为取得最佳 CV 分数的那组。
max_depth = {2,3,4},min_samples_leaf = {0.05, 0.1}# Import DecisionTreeClassifier
from sklearn.tree import DecisionTreeClassifier
# Set seed to 1 for reproducibility
SEED = 1
# Instantiate a DecisionTreeClassifier 'dt'
dt = DecisionTreeClassifier(random_state=SEED)
# 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'}
# 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)
# 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
# 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 树模型机器学习