GLMNET包中二项式目标变量的交叉验证错误

6
这是关于https://stats.stackexchange.com/questions/72251/an-example-lasso-regression-using-glmnet-for-binary-outcome的问题。我正在尝试在GLMNET中使用交叉验证(即cv.glmnet)来处理二项目标变量。虽然glmnet可以正常工作,但cv.glmnet会抛出一个错误。以下是错误日志:
Error in storage.mode(y) = "double" : invalid to change the storage mode of a factor
In addition: Warning messages:

1: In Ops.factor(x, w) : ‘*’ not meaningful for factors
2: In Ops.factor(y, ybar) : ‘-’ not meaningful for factors

数据类型:

'data.frame':   490 obs. of  13 variables:

$ loan_id          : Factor w/ 614 levels "LP001002","LP001003",..: 190 381 259 310 432 156 179 24 429 408 ...
$ gender           : Factor w/ 2 levels "Female","Male": 2 2 2 2 2 2 2 2 2 1 ...
$ married          : Factor w/ 2 levels "No","Yes": 2 2 2 2 1 2 2 2 2 1 ...
$ dependents       : Factor w/ 4 levels "0","1","2","3+": 1 1 1 3 1 4 2 3 1 1 ...
$ education        : Factor w/ 2 levels "Graduate","Not Graduate": 1 1 1 2 1 1 1 2 1 2 ...     
$ self_employed    : Factor w/ 2 levels "No","Yes": 1 1 1 1 1 1 1 1 1 1 ...
$ applicantincome  : int  9328 3333 14683 7667 6500 39999 3750 3365 2920 2213 ...
$ coapplicantincome: num  0 2500 2100 0 0 ...
$ loanamount       : int  188 128 304 185 105 600 116 112 87 66 ...
$ loan_amount_term : Factor w/ 10 levels "12","36","60",..: 6 9 9 9 9 6 9 9 9 9 ...
$ credit_history   : Factor w/ 2 levels "0","1": 2 2 2 2 2 2 2 2 2 2 ...
$ property_area    : Factor w/ 3 levels "Rural","Semiurban",..: 1 2 1 1 1 2 2 1 1 1 ...
$ loan_status      : Factor w/ 2 levels "0","1": 2 2 1 2 1 2 2 1 2 2 ...

所使用的代码:

xfactors<-model.matrix(loan_status ~ gender+married+dependents+education+self_employed+loan_amount_term+credit_history+property_area,data=data_train)[,-1]
x<-as.matrix(data.frame(applicantincome,coapplicantincome,loanamount,xfactors))
glmmod<-glmnet(x,y=as.factor(loan_status),alpha=1,family='binomial')
plot(glmmod,xvar="lambda")
grid()

cv.glmmod <- cv.glmnet(x,y=loan_status,alpha=1) #This Is Where It Throws The Error

4
我猜您需要在 cv.glmnet 函数中也加入 family。以下是示例:x <- model.matrix(am ~ 0 + . , data=mtcars) cv.glmnet(x, y=factor(mtcars$am), alpha=1) cv.glmnet(x, y=factor(mtcars$am), alpha=1, family="binomial") - user20650
感谢 user20650,它像魔法一样运行良好。 - Anurag H
@user20650 在这种情况下,“am”是做什么用的? - Adam Ralphus
@AdamRalphus;这只是一些示例数据:am是来自mtcars$am的二进制变量,除此之外它与glmnet无关。 - user20650
谢谢您回答我的问题。我对glmnet()还不太熟悉。如果我有进一步的问题,我有什么方法可以联系到您吗? - Adam Ralphus
显示剩余3条评论
1个回答

8

感谢@user20650提供的答案。

我猜你需要在cv.glmnet中添加family。以下是一个例子:

x <- model.matrix(am ~ 0 + . , data=mtcars)
cv.glmnet(x, y=factor(mtcars$am), alpha=1)
cv.glmnet(x, y=factor(mtcars$am), alpha=1, family="binomial")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接