首页 > 解决方案 > 带有插入符号的 R 特征选择 - 将结果图限制在前 10 位,并将完整结果存储到数据框中

问题描述

我对 R 比较陌生,并且第一次尝试进行特征选择。我遵循了一个使用 PimaIndiansDiabetes 数据集作为示例的在线教程。我在自己的数据集上重复了本教程中的步骤,该数据集具有 110 多个特征。

我已经包含了我在下面使用的教程的示例代码。唯一的区别是我的代码具有更大的数据集和不同的命名约定。

当我为自己的结果绘制重要性值时,图中出现了 110 多个项目。有人知道我如何将其限制在前 10 名吗?

library(mlbench)
library(caret)
# ensure results are repeatable
set.seed(7)

# load the dataset
data(PimaIndiansDiabetes)

# prepare training scheme
control <- trainControl(method="repeatedcv", number=10, repeats=3)

# train the model
model <- train(diabetes~., data=PimaIndiansDiabetes, method="lvq", 
preProcess="scale", trControl=control)

# estimate variable importance
importance <- varImp(model, scale=FALSE)

# summarize importance

print(importance)

# plot importance
plot(importance)

我还希望能够将这些完整结果存储到数据框中。我尝试了以下命令:

importanceDF <- as.data.frame(importance)

但我收到以下错误

Error in as.data.frame.default(importance) : 
    cannot coerce class ""varImp.train"" to a data.frame

抱歉,如果这是一个简单的问题,我已经尝试过谷歌搜索,但还没有找到有效的答案。

提前致谢,

艾米

编辑:

根据 zacdav 的回答,我应用了以下逻辑:

importance$importance
temp <- importance
temp$importance <- importance$importance[1:5, ]
plot(temp)

但是我注意到当我最初运行情节时(重要性)

样本数据中的顺序如下:

             Importance
glucose      0.7881
mass         0.6876
age          0.6869
pregnant     0.6195
pedigree     0.6062
pressure     0.5865
triceps      0.5536
insulin      0.5379

然后当我运行 temp$importance <-importance$importance[1:5, ] plot(temp)

我得到以下命令:

glucose
pregnant
pressure
triceps
insulin

这是根据它们在原始表中的显示方式而不是基于它们的重要性来获取前 5 行。

我尝试运行以下命令:

# put into DF
 importanceDF <- importance$importance
# sort
importanceDF_Ordered <- importanceDF[order(-importanceDF$neg),] 
temp <- importanceDF_Ordered 

最后一行然后给出一个错误:

Error in `$<-.data.frame`(`*tmp*`, "importance", value = list(neg = 
 c(0.619514925373134,  : 
  replacement has 5 rows, data has 8

标签: rplotr-caretfeature-selection

解决方案


查看重要性对象的结构,您会看到它是一个包含三个元素的列表,一个包含每个响应类的重要性值的 data.frame 和其他元数据。您可以使用$符号索引 data.frame。

str(importance)

List of 3
 $ importance:'data.frame': 8 obs. of  2 variables:
  ..$ neg: num [1:8] 0.62 0.788 0.586 0.554 0.538 ...
  ..$ pos: num [1:8] 0.62 0.788 0.586 0.554 0.538 ...
 $ model     : chr "ROC curve"
 $ calledFrom: chr "varImp"
 - attr(*, "class")= chr "varImp.train"

因此,要获取 data.frame,您需要做的就是importance$importance

至于调整此对象,以便您可以绘制可以调整对象的特征子集。我建议也许制作一个副本,以便不需要重新运行分析。一个粗略的例子如下:

temp <- importance
temp$importance <- importance$importance[1:5, ]
plot(temp)

我选择使用1:5data.frame 上的行索引绘制前五个以覆盖临时对象 data.frame。如果您有兴趣直接调用 plot 方法,请使用caret:::plot.varImp.train


推荐阅读