交叉验证统计
您已经使用网格搜索交叉验证(grid search CV)来调优随机森林分类器,现在希望检查交叉验证结果,确保没有过拟合。具体来说,您想计算每个折的平均测试得分与平均训练得分之间的差值。数据集已作为 X_train 和 y_train 提供,管道为 pipe,并且已预加载了若干模块,包括将 pandas 导入为 pd 和 GridSearchCV()。
本练习是课程的一部分
用 Python 设计机器学习工作流
练习说明
- 创建一个含 3 折交叉验证的网格搜索对象,并确保其同时返回训练与测试统计量。
- 将该网格搜索对象拟合到训练数据上。
- 将已拟合的交叉验证对象的
cv_results_属性中的交叉验证结果保存到一个数据框中。 - 打印包含平均测试得分的列与包含平均训练得分的列之间的差值。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Fit your pipeline using GridSearchCV with three folds
grid_search = GridSearchCV(
pipe, params, ____=3, return_train_score=____)
# Fit the grid search
gs = grid_search.____(____, ____)
# Store the results of CV into a pandas dataframe
results = pd.____(gs.____)
# Print the difference between mean test and training scores
print(
results[____]-results['mean_train_score'])