网格搜索
简单说,就是将所有可调的参数,组成一个网格表,训练过程会自动选出最优模型参数:
以决策树模型为例,拟合样本数据。
这个初始模型会过拟合。 然后,我们将使用网格搜索为这个模型找到更好的参数,以减少过拟合。
首先,导入:
1.阅读并绘制数据
现在,这个函数将帮助我们读取 csv 文件并绘制数据。
2. 将我们的数据分为训练和测试集
3. 拟合一个决策树模型
现在我们来绘制模型,并找到测试 f1_score
以下函数将帮助我们绘制模型。
The Training F1 Score is 1.0
The Testing F1 Score is 0.7
由上图知,现在的模型明显是过拟合的。 我们不仅仅是看图表,还需要看看高训练分(1.0)和低测试分(0.7)之间的差异。思考一下,我们是否可以找到更好的超参数来让这个模型做得更好? 接下来我们将使用网格搜索。
4.使用网格搜索来完善模型
现在,我们将执行以下步骤:
1.首先,定义一些参数来执行网格搜索。 我们建议使用max_depth
, min_samples_leaf
, 和 min_samples_split
。
2.使用f1_score
,为模型制作记分器。
3.使用参数和记分器,在分类器上执行网格搜索。
4.将数据拟合到新的分类器中。
5.绘制模型并找到 f1_score。
6.如果模型不太好,请尝试更改参数的范围并再次拟合。
获得最佳估算模型,用最佳估算器重新拟合参数,并统计参数得分;
- 总结
注意,通过使用网格搜索,我们将 F1 分数从 0.7 提高到 0.8(同时我们失去了一些训练分数,但这没问题)。 另外,如果你看绘制的图,第二个模型的边界更为简单,这意味着它不太可能过拟合。