用 GridSearchCV 寻找最优参数
在本练习中,您将不再「随意」微调模型,而是用 GridSearchCV 来帮您系统搜索。
使用 GridSearchCV,您可以指定用于评分的性能指标。针对欺诈检测,我们更关注尽可能多地捕获欺诈样本,因此可以将模型调优为尽可能提高召回率(Recall)。如果您同样关心减少误报数量,也可以优化 F1 分数,以在精确率与召回率之间做权衡。
GridSearchCV 已从 sklearn.model_selection 导入,试试看吧!
本练习是课程的一部分
Python 中的欺诈检测
练习说明
- 在参数网格中设定要尝试 1 和 30 棵树,并尝试
gini与entropy两种划分准则。 - 将模型定义为简单的 RandomForestClassifier,并将 random_state 设为 5,以便比较模型。
- 设置
scoring选项,使其以召回率为优化目标。 - 将模型拟合到训练数据
X_train和y_train,并获取该模型的最优参数。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Define the parameter sets to test
param_grid = {'n_estimators': [____, ____], 'max_features': ['auto', 'log2'], 'max_depth': [4, 8], 'criterion': ['____', '____']
}
# Define the model to use
model = ____(random_state=5)
# Combine the parameter sets with the defined model
CV_model = GridSearchCV(estimator=model, param_grid=param_grid, cv=5, scoring='____', n_jobs=-1)
# Fit the model to our training data and obtain best parameters
CV_model.fit(____, ____)
CV_model.____