在尝试进行模型调优时,我得到的分数比之前还要差。以下是我的代码:
调优前
rf_model = RandomForestRegressor(random_state=42).fit(X_train, y_train)y_pred = rf_model.predict(X_test)rmse = np.sqrt(mean_squared_error(y_test, y_pred))rmse
结果是:344.73852779396566
但是当我尝试使用GridSearchCV时,
rf_params = {"max_depth":[5,8,10], "max_features":[2,5,10], "n_estimators":[200,500,100,2000], "min_samples_split":[2,10,80]}rf_cv = GridSearchCV(rf_model, rf_params, cv = 10, verbose = 2, n_jobs=-1).fit(X_train, y_train)rf_cv.best_params_
它给出了最佳参数如下:
{'max_depth': 8, 'max_features': 2, 'min_samples_split': 2, 'n_estimators': 200}
然后我用这些参数再次训练模型:
调优后
rf_tunned = RandomForestRegressor(max_depth=8, max_features = 2, min_samples_split = 2, n_estimators = 200).fit(X_train, y_train)y_pred = rf_tunned.predict(X_test)rmse = np.sqrt(mean_squared_error(y_test, y_pred))rmse
结果是rmse:350.14634045283685
这种情况的原因是什么?我们不是使用模型调优来获得更好的结果吗?
回答:
需要注意以下两点:
-
通过简单运行
RandomForestRegressor(random_state=42)
,你回到了所有参数(除了random_state
)的默认值,如文档中所述。 -
网格搜索并不是“魔法”或包罗万象的;它只会测试你在范围内指定的参数组合。
检查文档中参数的默认值,发现你的RandomForestRegressor(random_state=42)
运行实际上相当于以下参数设置:
{'max_depth': None, # 完整树深度 'max_features': 20, # 所有特征(默认) 'min_samples_split': 2, 'n_estimators': 100}
这个组合没有包含在你为网格搜索指定的参数范围内,所以它从未被尝试过。因此,它实际上比你的特定网格搜索给出更好的误差并不奇怪。