【问题标题】:Random Forest tuning with RandomizedSearchCV使用 RandomizedSearchCV 进行随机森林调优
【发布时间】:2023-04-09 08:55:01
【问题描述】:

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

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_

谢谢你, 回复

【问题讨论】:

    标签: python random-forest grid-search


    【解决方案1】:

    将“评分”参数添加到 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)
    

    【讨论】:

    • 所以 RandomizedSearchCV 现在应该在内部与 RMSE 一起工作,对吧?然后我不明白我的结果。我得到rf_random.best_score_ 这个结果-13684.3。 RMSE通常不能为负数吗? @托比
    • 你几乎是正确的。它与 MSE(没有 Square)一起工作。但是,对于 Grid/Randomized/...SearchCV,它必须是负 MSE。这就是我使用 np.sqrt(-mean_score) 的原因。这里给出了否定的解释:stackoverflow.com/questions/21050110/….
    【解决方案2】:

    如果您想为每个 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_)
    

    【讨论】:

      猜你喜欢
      • 2014-08-11
      • 2018-12-12
      • 2013-07-05
      • 2016-09-09
      • 2019-11-13
      • 2015-07-30
      • 2021-04-29
      • 2012-08-10
      • 2017-03-15
      相关资源
      最近更新 更多