我的总体目标是确定在波士顿数据集上执行的 Superlearner 的变量重要性。但是,当我尝试使用 R 中的 VIP 包确定变量重要性时,我收到以下错误。我怀疑包含 SuperLeaner 对象的预测包装器是导致错误的原因,但我不确定。
# Call:
# SuperLearner(Y = y_train, X = x_train, family = binomial(), SL.library = # c("SL.mean",
# "SL.glmnet", "SL.ranger"), method = "method.AUC")
# Risk Coef
# SL.mean_All 0.55622189 0.3333333
# SL.glmnet_All 0.06240630 0.3333333
# SL.ranger_All 0.02745502 0.3333333
# Error in mean(actual == predicted, na.rm = FALSE): (list) object cannot be # coerced to type 'double'
# Traceback:
# 1. vi_permute(object = sl, method = "permute", feature_names = colnames,
# . train = x_train, target = y_holdout, metric = "accuracy",
# . type = "difference", nsim = 1, pred_wrapper = pred_wrapper)
# 2. vi_permute.default(object = sl, method = "permute", feature_names =
# colnames,
# . train = x_train, target = y_holdout, metric = "accuracy",
# . type = "difference", nsim = 1, pred_wrapper = pred_wrapper)
# 3. mfun(actual = train_y, predicted = pred_wrapper(object, newdata =
# train_x))
# 4. mean(actual == predicted, na.rm = FALSE)
我执行了以下操作:
library(MASS)
data(Boston, package = "MASS")
# Extract our outcome variable from the dataframe.
outcome = Boston$medv
# Create a dataframe to contain our explanatory variables.
data = subset(Boston, select = -medv)
set.seed(1)
# Reduce to a dataset of 150 observations to speed up model fitting.
train_obs = sample(nrow(data), 150)
# X is our training sample.
x_train = data[train_obs, ]
# Create a holdout set for evaluating model performance.
x_holdout = data[-train_obs, ]
# Create a binary outcome variable: towns in which median home value is > 22,000.
outcome_bin = as.numeric(outcome > 22)
y_train = outcome_bin[train_obs]
y_holdout = outcome_bin[-train_obs]
library(SuperLearner)
set.seed(1)
sl = SuperLearner(Y = y_train, X = x_train, family = binomial(),
SL.library = c("SL.mean", "SL.glmnet", "SL.ranger"), method = "method.AUC")
sl
colnames <- colnames(x_train)
pred_wrapper <- function(sl, newdata) {
predict(sl, x = as.matrix(y_holdout)) %>%
as.vector()
}
# Plot VI scores
library(vip)
p1 <- vi_permute(object = sl, method = "permute", feature_names = colnames, train = x_train,
target = y_holdout,
metric = "accuracy",
type = "difference",
nsim = 1,
pred_wrapper = pred_wrapper)