r - 使用 for 循环从模型集合中绘制变量重要性
问题描述
在尝试从模型集合中绘制变量重要性时,我一直遇到错误。
我已经安装了一组模型,现在我正在尝试为我安装的每个算法创建多个变量重要性图。我正在使用varImp()
插入符号中的函数来提取变量重要性,然后plot()
是它。为了适应模型的集合,我使用caretEnsemble
包。
感谢您的帮助,请参阅下面的代码示例。
# Caret ensemble is needed to produce list of models
library(caret)
library(caretEnsemble)
# Set algorithms I wish to fit
my_algorithms <- c("glmnet", "svmRadial", "rf", "nnet", "knn", "rpart")
# Define controls
my_controls <- trainControl(
method = "cv",
savePredictions = "final",
number = 3
)
# Run the models all at once with caretEnsemble
my_list_of_models <- caretEnsemble::caretList(Species ~ .,
data = iris,
trControl = my_controls,
methodList = my_algorithms)
# Subset models
list_of_algorithms <- my_list_of_models[my_algorithms]
# Create first for loop to extract variable importance via caret::varImp()
importance <- list()
for (algo in seq_along(list_of_algorithms)) {
importance[[algo]] <- varImp(list_of_algorithms[[algo]])
}
# Create second loop to go over extracted importance and plot it using plot()
importance_plots <- list()
for (imp in seq_along(importance)) {
importance_plots[[imp]] <- plot(importance[[imp]])
}
# Error occurs during the second for loop:
Error in data.frame(values = unlist(unname(x)), ind, stringsAsFactors = FALSE):arguments imply differing number of rows: 16,
解决方案
我已经提出了上述问题的解决方案,并决定将其发布为我自己的答案。我编写了一个小函数来绘制变量重要性,而不依赖于caret
辅助函数来创建绘图。我使用dotplot
andlevelplot
因为根据提供的算法caret
返回不同。data.frame
它可能不适用于不适合的不同算法和模型。
# Libraries ---------------------------------------------------------------
library(caret) # To train ML algorithms
library(dplyr) # Required for %>% operators in custom function below
library(caretEnsemble) # To train multiple caret models
library(lattice) # Required for plotting, should be loaded alongside caret
library(gridExtra) # Required for plotting multiple plots
# Custom function ---------------------------------------------------------
# The function requires list of models as input and is used in for loop
plot_importance <- function(importance_list, imp, algo_names) {
importance <- importance_list[[imp]]$importance
model_title <- algo_names[[imp]]
if (ncol(importance) < 2) { # Plot dotplot if dim is ncol < 2
importance %>%
as.matrix() %>%
dotplot(main = model_title)
} else { # Plot heatmap if ncol > 2
importance %>%
as.matrix() %>%
levelplot(xlab = NULL, ylab = NULL, main = model_title, scales = list(x = list(rot = 45)))
}
}
# Tuning parameters -------------------------------------------------------
# Set algorithms I wish to fit
# Rather than using methodList as provided above, I've switched to tuneList because I need to control tuning parameters of random forest algorithm.
my_algorithms <- list(
glmnet = caretModelSpec(method = "glmnet"),
rpart = caretModelSpec(method = "rpart"),
svmRadial = caretModelSpec(method = "svmRadial"),
rf = caretModelSpec(method = "rf", importance = TRUE), # Importance is not computed for "rf" by default
nnet = caretModelSpec(method = "nnet"),
knn = caretModelSpec(method = "knn")
)
# Define controls
my_controls <- trainControl(
method = "cv",
savePredictions = "final",
number = 3
)
# Run the models all at once with caretEnsemble
my_list_of_models <- caretList(Species ~ .,
data = iris,
tuneList = my_algorithms,
trControl = my_controls
)
# Extract variable importance ---------------------------------------------
importance <- lapply(my_list_of_models, varImp)
# Plotting variable immportance -------------------------------------------
# Create second loop to go over extracted importance and plot it using plot()
importance_plots <- list()
for (imp in seq_along(importance)) {
# importance_plots[[imp]] <- plot(importance[[imp]])
importance_plots[[imp]] <- plot_importance(importance_list = importance, imp = imp, algo_names = names(my_list_of_models))
}
# Multiple plots at once
do.call("grid.arrange", c(importance_plots))
推荐阅读
- java - Android 9.0 中的 ArrayIndexOutOfBoundsException
- c# - 将部分视图导出到文本文件
- ruby-on-rails - 如何将复选框中的信息返回到 Ruby 中的数据库
- jquery - xdan/datetimepicker:无法从点击事件更改时间
- r - 替换 R 中的子字符串并与数值冲突
- c - 如何在C中qsort一个dirent
- javascript - 如果选中其他框并取消隐藏ID,则Jquery向元素添加一个复选框
- python - 在 postgresql 或其他代码行的引号内列出必要的引号?
- rest - 即使用户在用户端点上列出,“租户 guid 的租户不存在”?
- android - 尝试使用 raycaster 而不是 OnMouseOver() 来显示 UI 文本而没有成功