使用 RandomizedSearchCV 调整随机森林

Random Forest tuning with RandomizedSearchCV

我有几个关于随机森林回归模型中的随机网格搜索的问题。我的参数网格如下所示:

random_grid = {'bootstrap': [True, False],
               'max_depth': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, None],
               'max_features': ['auto', 'sqrt'],
               'min_samples_leaf': [1, 2, 4],
               'min_samples_split': [2, 5, 10],
               'n_estimators': [130, 180, 230]}

我的 RandomizedSearchCV 代码如下:

# Use the random grid to search for best hyperparameters
# First create the base model to tune
from sklearn.ensemble import RandomForestRegressor
rf = RandomForestRegressor()
# Random search of parameters, using 3 fold cross validation, 
# search across 100 different combinations, and use all available cores
rf_random = RandomizedSearchCV(estimator = rf, param_distributions = random_grid, n_iter = 100, cv = 3, verbose=2, random_state=42, n_jobs = -1)
# Fit the random search model
rf_random.fit(X_1, Y)

有什么方法可以计算每个参数集的均方根吗?作为 R^2 分数,这对我来说会更有趣吗? 如果我现在想要获得最佳参数集,如下面打印的那样,我也会使用最低的 RMSE 分数。有什么办法吗?

rf_random.best_params_
rf_random.best_score_
rf_random.best_estimator_

谢谢, R

将 'scoring' 参数添加到 RandomizedSearchCV。

RandomizedSearchCV(scoring="neg_mean_squared_error", ...

可以找到其他选项in the docs

有了这个,您可以打印每个参数集的 RMSE,以及参数集:

cv_results = rf_random.cv_results_
for mean_score, params in zip(cv_results["mean_test_score"], cvres["params"]):
    print(np.sqrt(-mean_score), params)

如果要为每个 cv 的结果创建数据框,请使用以下命令。 如果您还需要训练数据集的结果,请将 return_train_score 设置为 True

rf_random = RandomizedSearchCV(estimator = rf, return_train_score = True)
import pandas as pd
df = pd.DataFrame(rf_random.cv_results_)