【问题标题】:Random Forest Regressor model in R?R中的随机森林回归模型?
【发布时间】:2022-11-11 02:11:31
【问题描述】:

我目前正在将 Python 用于随机森林回归模型:

rfr = RandomForestRegressor(random_state=42)

param_grid = {'bootstrap': [True],
 'max_depth': [10, 30, 50],
 'n_estimators': [200, 400, 600]}

CV = RandomizedSearchCV(estimator = rfr, param_distributions = param_grid, n_iter = 5, cv = 5, verbose=2, random_state=42, n_jobs = -1)

CV.fit(x_train, y_train)

print('best model:', CV.best_params_,'\nbest score: %.2f' % CV.best_score_)

如何在 R 中重新编码它们?特别是对于 rfr、param_grid 和 CV?

【问题讨论】:

    标签: python r random-forest


    【解决方案1】:

    你最好的选择是caret 包。这个包并没有真正的模型,它就像一个框架。例如,当您训练 caret 模型时,默认模型来自 randomForest::randomForest

    不需要或不推荐编码。我不知道任何需要您在 R 中对分类数据进行编码的模型。但是,确保数据中的数据类型正确始终很重要。

    没有使用这些方法的实例化。

    以下是您想要查看的几个关键函数以及为什么在 caret 库中。

    • createDataPartition:拆分数据;培训/测试/验证(随心所欲)
    • train: 训练模型
    • trainControl:用于设置是否要引导、交叉验证、重复交叉验证(以及更多)、您想做多少次以及重复多少次。
    • modelLookup:这将告诉您想要为您选择的模型类型设置的控件。比如你想用randomForest::randomForestmodelLookup告诉我们你只能网格mtry;如果您使用ranger::ranger(另一个图书馆的随机森林),modelLookup 告诉我们您可以网格化mtrysplitrulemin.node.size。 (这两种随机森林模型都适用于分类和回归。)

    caret 有一个很棒的数字手册,但它有点过时了(我相信现在有更多模型;我认为也有一些具有不同默认值的模型)。 You can find that here.

    在我的示例中,我将使用ranger。 在ranger 模型中:

    • n_estimators 等价于 num.trees
    • max_depth 等价于 max.depth

    此外,当方法设置为ranger 时,可以将?ranger::ranger 的帮助中显示的所有参数添加到train()

    运行此代码时,您不需要调用库ranger,但您必须安装包。

    从一些数据和数据准备开始(任意选择)。

    library(tidyverse)
    library(caret)
    
    data("midwest")
    
    midwest <- midwest[, c(3:6, 17:20, 27)] %>% 
      mutate(state = factor(state), inmetro = factor(inmetro))
    

    现在,我要将数据拆分为 70/30 的验证集。

    # by setting a char/factor field, it's automatically stratified
    set.seed(35)
    tr <- createDataPartition(midwest$state, p = .7, list = F)
    

    我将向您展示如何使用modelLookup 来找到您想要使用的模型。例如,如果您想查看哪些模型使用了包含“深度”一词的参数。 (模型可以是基于决策树、神经网络或任何其他类型的模型;假设永远不安全!)

    modelLookup() %>% 
      filter(str_detect(parameter, "depth"))
    #          model         parameter              label forReg forClass probModel
    # 1          ada          maxdepth     Max Tree Depth  FALSE     TRUE      TRUE
    # 2       AdaBag          maxdepth     Max Tree Depth  FALSE     TRUE      TRUE
    # 3  AdaBoost.M1          maxdepth     Max Tree Depth  FALSE     TRUE      TRUE
    # 4   blackboost          maxdepth     Max Tree Depth   TRUE     TRUE      TRUE
    # 5      bstTree          maxdepth     Max Tree Depth   TRUE     TRUE     FALSE
    # 6       ctree2          maxdepth     Max Tree Depth   TRUE     TRUE      TRUE
    # 7    deepboost        tree_depth         Tree Depth  FALSE     TRUE     FALSE
    # 8          gbm interaction.depth     Max Tree Depth   TRUE     TRUE      TRUE
    # 9      gbm_h2o         max_depth     Max Tree Depth   TRUE     TRUE      TRUE
    # 10         pre          maxdepth     Max Tree Depth   TRUE     TRUE      TRUE
    # 11      rFerns             depth         Fern Depth  FALSE     TRUE     FALSE
    # 12     rfRules          maxdepth Maximum Rule Depth   TRUE     TRUE     FALSE
    # 13      rpart2          maxdepth     Max Tree Depth   TRUE     TRUE      TRUE
    # 14     xgbDART         max_depth     Max Tree Depth   TRUE     TRUE      TRUE
    # 15     xgbTree         max_depth     Max Tree Depth   TRUE     TRUE      TRUE 
    
    # forReg means for regression; forClass means for classification; prob means probability
    

    正如我所说,我将使用ranger

    modelLookup("ranger")
    #    model     parameter                         label forReg forClass probModel
    # 1 ranger          mtry #Randomly Selected Predictors   TRUE     TRUE      TRUE
    # 2 ranger     splitrule                Splitting Rule   TRUE     TRUE      TRUE
    # 3 ranger min.node.size             Minimal Node Size   TRUE     TRUE      TRUE 
    

    使用这些信息,我可以创建我的调整网格。

    tG <- expand.grid(mtry = c(3, 4, 6),                       # variables to split
                      splitrule = c("extratrees", "variance"), # model training btw splits
                      min.node.size = c(3, 5, 7))              # min qty obs at each node
    

    我将设置重复的交叉验证。

    # establish how to train
    tC <- trainControl(method = "repeatedcv", repeats = 5)
    

    是时候训练模型了。我想指出,我在train 中记录参数的方式与train 函数记录的内容部分相关,但参数

    # using formula (that's tilde period comma to say 'and everything else')
    set.seed(35)
    fit <- train(poptotal~.,  
                 data = midwest[tr, ], tuneGrid = tG, trControl = tC,
                 method = "ranger", importance = "permutation", 
                 scale.permutation.importance = T)
    # Random Forest 
    # 
    # 309 samples
    #   8 predictor
    # 
    # No pre-processing
    # Resampling: Cross-Validated (10 fold, repeated 5 times) 
    # Summary of sample sizes: 281, 278, 277, 277, 277, 278, ... 
    # Resampling results across tuning parameters:
    # 
    #   mtry  splitrule   min.node.size  RMSE       Rsquared   MAE     
    #   3     extratrees  3               97994.57  0.9540533  23562.39
    #   3     extratrees  5               99066.61  0.9523176  24111.05
    #   3     extratrees  7               99757.54  0.9495842  24535.54
    #   3     variance    3              114908.64  0.8855597  28326.62
    #   3     variance    5              116839.06  0.8762747  28883.57
    #   3     variance    7              116378.17  0.8766985  29118.59
    #   4     extratrees  3               92825.54  0.9693964  20950.30
    #   4     extratrees  5               93879.65  0.9677459  21342.85
    #   4     extratrees  7               94963.99  0.9653268  21856.72
    #   4     variance    3              108533.52  0.9188248  25262.68
    #   4     variance    5              111004.38  0.9047721  26059.75
    #   4     variance    7              111046.46  0.9068934  26089.53
    #   6     extratrees  3               89392.68  0.9779004  18832.46
    #   6     extratrees  5               90215.15  0.9764424  19059.87
    #   6     extratrees  7               91033.46  0.9753090  19408.73
    #   6     variance    3              101022.50  0.9531625  21934.87
    #   6     variance    5              100856.81  0.9541640  21965.35
    #   6     variance    7              102664.47  0.9506119  22347.86
    # 
    # RMSE was used to select the optimal model using the smallest value.
    # The final values used for the model were mtry = 6, splitrule = extratrees and min.node.size = 3. 
    

    我可以在没有所有额外信息的情况下对该模型的性能进行排队,查看 Ranger 如何对结果进行评分,并查看验证集上的预测。

    p.tr <- predict.train(fit)                   # collect predicted values
    postResample(p.tr, midwest[tr, ]$poptotal)   # calculate metrics
    #         RMSE     Rsquared          MAE 
    # 9.928424e+04 9.710269e-01 7.736478e+03  
    
    fit$finalModel # DRASTICALLY different; these metrics are based on OOB!
    
    # validation data
    p.ts <- predict(fit, midwest[-tr, ])        # collect predicted values
    postResample(p.ts, midwest[-tr, ]$poptotal) # calculate metrics
    #         RMSE     Rsquared          MAE 
    # 5.844063e+04 9.528124e-01 1.561766e+04  
    

    【讨论】:

      猜你喜欢
      • 2013-07-23
      • 2020-02-25
      • 2021-03-21
      • 2020-03-18
      • 2019-12-06
      • 2013-07-22
      • 2018-12-06
      • 2019-10-23
      • 2015-12-23
      相关资源
      最近更新 更多