[英]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.