【发布时间】:2020-03-31 14:23:03
【问题描述】:
我打算使用care::sbf 进行单变量特征选择,其中我的输入是具有多个变量(又名,它的列)、候选特征列表和标签(又名,分类变量)的数据框。在阅读了caret 包文档后,我尝试使用sbf、sbfController 进行功能选择,但在下面遇到了错误:
contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]]) 中的错误:
对比只能应用于具有 2 个或更多级别的因素
谁能告诉我如何解决这个错误?使用caret::sbf 进行特征选择的正确方法是什么?有什么想法吗?
可重现的例子:
这里是reproducible example on public gist,我用它作为输入。
我目前的尝试:
library(caret)
library(e1071)
library(randomForest)
df=read.csv("df.csv", header=True)
sbfCtrl <- sbfControl(method = 'cv', number = 10, returnResamp = 'final', functions = caretFuncs, saveDetails = TRUE)
model <- sbf(form= ventil_status~ .,
data= df,
methods='knn',
trControl=trainControl(method = 'cv', classProbs = TRUE),
tuneGrid=data.frame(k=1:10),
sbfControl=sbfControl(functions = sbfCtrl,
methods='repeatedcv', number = 10, repeats = 10))
print(model)
print(model$fit$results)
> model <- sbf(ventil_status~ ., data=df, sizes=c(1,5,10,20),
+ method= 'knn', trControl=trainControl(method = 'cv', classProbs = TRUE),
+ tuneGrid = data.frame(k=1:10),
+ sbfControl=sbfCtrl)
Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
contrasts can be applied only to factors with 2 or more levels
我用谷歌搜索了这个错误,但仍然无法克服它。任何想法使上述代码工作?使用caret::sbf 进行过滤器选择的正确方法是什么?
我想要的是输出数据框必须具有附加的 p 值的选定特征。所以这是我的尝试:
newdf <- df[ , -which(names(df) %in% c("subject"))]
p_value_vector <- sapply(names(newdf), function(i)
tryCatch(
wilcox.test(newdf[newdf$ventil_status %in% "0", i],
newdf[newdf$ventil_status %in% "1", i],
na.action(na.omit))$p.value),
warning = function(w) return(NA),
error = function (e) return(NA)
)
预期输出:
我期望输出具有选定特征的数据框,其中 wilcox.test 返回的 p 值应附加到相应的特征。有什么想法可以在 r 中实现吗?如何正确使用caret::sbf 操作特征选择?任何想法?
这是我的 R 会话信息:
> sessionInfo()
R version 3.6.3 (2020-02-29)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18362)
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] ggpubr_0.2.5 magrittr_1.5 reshape2_1.4.3
[4] forcats_0.5.0 purrr_0.3.3 readr_1.3.1
[7] tibble_2.1.3 tidyverse_1.3.0 stringr_1.4.0
[10] dplyr_0.8.5 scales_1.1.0 tidyr_1.0.2
[13] aws.s3_0.3.20 randomForest_4.6-14 e1071_1.7-3
[16] mlbench_2.1-1 caret_6.0-86 ggplot2_3.3.0
[19] lattice_0.20-38
【问题讨论】:
-
@StupidWolf 我试图理解你的答案,但有一件事让我印象深刻,在这个脚本中:
knnSBF$filter <- function(score, x, y) { score <= 0.05 },其中不使用参数x,y,仍然考虑model1$optVariables作为过滤功能?你能详细说明这一点吗?谢谢 -
是sbf的写法,如果你看底层代码github.com/topepo/caret/blob/master/pkg/caret/R/…,有一行保留了这一行
-
@StupidWolf 而不是使用
p_value_vector,我们不能使用knnSBF$score来过滤特征吗?由于wilcox.text返回p-value,如何直接访问model1$optVariables的p-value? -
你想怎么用?
-
data.frame(model1$optVariables,p_value_vector[model1$optVariables])
标签: r statistics r-caret feature-extraction statistical-test