繁体   English   中英

从 mlr 包的重采样 function 中获取特定的随机森林变量重要性度量

[英]Getting a specific random forest variable importance measure from mlr package's resample function

我正在使用mlr包的resample() function 对随机森林 model 进行子采样 4000 次(下面的代码片段)。

如您所见,要在resample()中创建随机森林模型,我使用的是randomForest package。

我想获得每个子样本迭代的随机森林模型的重要性结果(所有类的准确性平均下降)。 作为重要性衡量标准,我现在可以得到的是基尼指数的平均下降。

What I can see from the source code of mlr, getFeatureImportanceLearner.classif.randomForest() function (line 69) in makeRLearner.classif.randomForest uses randomForest::importance() function (line 83) to get importance value from the resulting object of随机森林 class randomForest 但是从源代码(第 73 行)可以看出,它使用 2L 作为默认值。 我希望它使用 1L(第 75 行)作为值(平均精度下降)。

如何将 2L 的值传递给resample() function,(下面代码中的“extract = getFeatureImportance”行)以便getFeatureImportanceLearner.classif.randomForest() function 获取该行值并设置ctrl$type = 2L ?

rf_task <- makeClassifTask(id = 'task',
                           data = data[, -1], target = 'target_var',
                           positive = 'positive_var')

rf_learner <- makeLearner('classif.randomForest', id = 'random forest',
                          par.vals = list(ntree = 1000, importance = TRUE),
                          predict.type = 'prob')

base_subsample_instance <- makeResampleInstance(rf_boot_desc, rf_task)

rf_subsample_result <- resample(rf_learner, rf_task,
                                base_subsample_instance,
                                extract = getFeatureImportance,
                                measures = list(acc, auc, tpr, tnr,
                                                ppv, npv, f1, brier))

我的解决方案:下载了 mlr package 的源代码。 将源文件第 73 行更改为 1L ( https://github.com/mlr-org/mlr/blob/v2.15.0/R/RLearner_classif_randomForest.R )。 从命令行安装 package 并使用它。 不是最佳解决方案,而是解决方案。

您提供了许多实际上与您的问题无关的细节,至少我是如何理解的。 所以我写了一个包含答案的简单 MWE。 这个想法是您必须为getFeatureImportance编写一个简短的包装器,以便您可以传递自己的 arguments。 purrr的粉丝可以使用purrr::partial(getFeatureImportance, type = 2)来做到这一点,但在这里我手动编写了myExtractor

library(mlr)
rf_learner <- makeLearner('classif.randomForest', id = 'random forest',
                          par.vals = list(ntree = 100, importance = TRUE),
                          predict.type = 'prob')

measures = list(acc, auc, tpr, tnr,
                ppv, npv, f1, brier)

myExtractor = function(.model, ...) {
  getFeatureImportance(.model, type = 2, ...)
}

res = resample(rf_learner, sonar.task, cv10, 
               measures = measures, extract = myExtractor)

# first feature importance result:
res$extract[[1]]

# all values in a matrix:
sapply(res$extract, function(x) x$res)

如果你想做一个引导学习者,也许你还应该看看makeBaggingWrapper而不是通过resample解决这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM