微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

LASSO的R功能选择

如何解决LASSO的R功能选择

我有一个小的数据集(37个观测值x 23个特征),并希望通过LASSO回归进行特征选择,以减小其维数。为此,我根据在线教程设计了以下代码

#Load the libraries
library(mlbench)
library(elasticnet)
library(caret)

#Initialize cross validation and train LASSO
cv_5 <- trainControl(method="cv",number=5)
lasso <- train( ColumnY ~.,data=My_Data_Frame,method='lasso',trControl=cv_5)

#Filter out the variables whose coefficients have squeezed to 0
drop <-predict.enet(lasso$finalModel,type='coefficients',s=lasso$bestTune$fraction,mode='fraction')$coefficients  
drop<-drop[drop==0]%>%names()
My_Data_Frame<- My_Data_Frame%>%select(-drop) 

在大多数情况下,代码可以正常运行,但偶尔会引发以下情况:

Warning messages:
1: model fit Failed for Fold2: fraction=0.9 Error in if (zmin < gamhat) { : missing value where TRUE/FALSE needed
 
2: In nominalTrainWorkflow(x = x,y = y,wts = weights,info = trainInfo,:
  There were missing values in resampled performance measures.

我之所以会这样,是因为我的数据行很少,而某些变量的方差很小。 有什么方法可以绕过或解决此问题(例如,在流程中设置参数)?

解决方法

您的观察值较少,因此在某些训练集中很有可能您的某些列全为零或方差很小。例如:

library(caret)
set.seed(222)
df = data.frame(ColumnY = rnorm(37),matrix(rbinom(37*23,1,p=0.15),ncol=23))

cv_5 <- trainControl(method="cv",number=5)
lasso <- train( ColumnY ~.,data=df,method='lasso',trControl=cv_5)

Warning messages:
1: model fit failed for Fold4: fraction=0.9 Error in elasticnet::enet(as.matrix(x),y,lambda = 0,...) : 
  Some of the columns of x have zero variance

在下面运行之前,请检查类别列是否全部都没有1个正标签。

一种方法是增加简历倍数,如果您设置为5,则将使用80%的数据。尝试10使用90%的数据:

cv_10 <- trainControl(method="cv",number=10)
lasso <- train( ColumnY ~.,trControl=cv_10)

正如您可能已经看到的..由于数据集非常小,交叉验证可能不会为您提供太多优势,因此您也可以省略交叉验证:

tr <- trainControl(method="LOOCV")
lasso <- train( ColumnY ~.,trControl=tr)
,

您可以使用 FSinR 包来执行特征选择。它在 R 中,可从 CRAN 访问。它具有多种过滤器和包装器方法,您可以将它们与搜索方法结合使用。生成包装器求值器的接口遵循插入符接口。例如:

# Load the library
library(FSinR)

# Choose one of the search methods
searcher <- searchAlgorithm('sequentialForwardSelection')

# Choose one of the filter/wrapper evaluators (You can remove the fitting and resampling params if you want to make it simpler)(These are the parameters of the train and trainControl of caret)
resamplingParams <- list(method = "cv",number = 5)
fittingParams <- list(preProc = c("center","scale"),metric="Accuracy",tuneGrid = expand.grid(k = c(1:20)))
evaluator <- wrapperEvaluator('knn',resamplingParams,fittingParams)

# You make the feature selection (returns the best features)
results <- featureSelection(My_Data_Frame,'ColumnY',searcher,evaluator)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。