I keep running into an error while attempting to plot variable importance from ensemble of models.
I have ensemble of models I've fitted and now I am trying to create multiple variable importance plots for each algorithm I've fitted. I am using varImp() function from caret to extract variable importance, then plot() it. To fit ensemble of models, I am using caretEnsemble package.
Thank you for any help, please see the example of code below.
# 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,
importance_plotsnot a regular list? Also, why not usingimportance_plots <- lapply(importance, function(imp){ plot(importance(imp)) })? - mikakeplot.varImp.trainplot method, and that the class ofimportance[[4]]isvarImp.train, it looks like there is a bug in the code (as in a bug in caret). You could submit it on github to get fixed. Other than that, you can usedotplotandimportance[[4]]$importanceto plot it yourself. Also, native R plots cannot be saved to variables. - LyzandeRlist(), I've edited the code. I have tried lapply solution but it doesn't work as there might be a bug incaretas suggested by @LyzandeR I also trieddotplotsolution butvarImpextracts different data.frame objects. As a resultdotplotdoesn't know how to treat it and I would have to play around with it more. Thanks to both of you. - gofraidh