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

标签 r glmnet

这是引用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

最佳答案

答案归功于@user20650。

怀疑您还需要将family添加到cv.glmnet。一个例子:

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")

关于r - GLMNET 包 R 中二项式目标变量的交叉验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35247522/

相关文章:

r - 在散点图中绘制 95% 置信限

在 R 中运行 glmnet 包,得到错误 "missing value where TRUE/FALSE needed",可能是由于缺少值?

r - 当 R 中的 glm 函数可以时,为什么不能只将 1 列传递给 glmnet?

使用 R 重命名 windows 文件夹中的多个文件

r - 使用Rocker调试R软件包(如何更改版本?)

r - 具有 3 个分类变量的条形图

r - 系列中第一个新元素的虚拟

r - 使用 glm.fit 、 bigglm、 speedglm、 glmnet、 LiblineaR 对逻辑回归进行基准测试

r - glmnet 给出与输入不同的 lambda 值序列

r - glmnet中的自动插入符号参数调整失败