使用 GridSearchCV 和 StratifiedKFold 优化 GradientBoostingClassifier
这是一个使用 GradientBoostingClassifier 进行网格搜索交叉验证的代码。其目的是为了找到最优的学习率和最大深度参数。具体实现步骤如下:
-
定义一个 GradientBoostingClassifier 模型,将 n_estimators 设置为 300,random_state 设置为 123。
-
定义一个参数网格 param_grid,包含了学习率和最大深度两个参数的取值范围。
-
使用 StratifiedKFold 进行交叉验证,将数据集分为 10 份,其中每一份保持类别比例不变。
-
使用 GridSearchCV 进行网格搜索,传入模型、参数网格、交叉验证方法等参数,返回最优的参数组合。
-
在最优参数组合下,使用训练集进行模型训练,使用测试集进行模型评估。
-
输出最优参数组合和模型评估结果。
代码示例如下:
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import GridSearchCV, StratifiedKFold
# 定义模型,n_estimators=300, random_state=123
model = GradientBoostingClassifier(n_estimators=300, random_state=123)
# 定义参数网格,包含 learning_rate 和 max_depth 两个参数的取值范围
param_grid = {
'learning_rate': [0.1, 0.2, 0.3, 0.4, 0.5],
'max_depth': range(1, 10)
}
# 定义交叉验证方法,StratifiedKFold 将数据集分为 10 份,保持类别比例不变
cv = StratifiedKFold(n_splits=10, random_state=1, shuffle=True)
# 使用 GridSearchCV 进行网格搜索,传入模型、参数网格、交叉验证方法等参数
grid_search = GridSearchCV(model, param_grid, cv=cv)
# 对训练集进行网格搜索交叉验证,返回最优的参数组合
grid_search.fit(X_train, y_train)
# 输出最优参数组合
print('Best parameters: ' + str(grid_search.best_params_))
# 在最优参数组合下,使用训练集进行模型训练,使用测试集进行模型评估
best_model = grid_search.best_estimator_
y_pred = best_model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
# 输出模型评估结果
print('Accuracy: {:.2f}'.format(accuracy))
原文地址: https://www.cveoy.top/t/topic/oJ8x 著作权归作者所有。请勿转载和采集!