我在训练数据上开发了一个 LASSO 模型来预测 R 中的二元响应变量,使用交叉验证来选择我的 $\lambda$:
x = model.matrix(y ~ x1 + x2 + ... + x23, data=train)[, -1]
library(glmnet)
glm.train = glmnet(x, y = as.factor(train$y), alpha = 1, family = 'binomial')
plot(glm.train, xvar = "lambda")
grid()
glm.train.cv = cv.glmnet(x, y = train$dem, alpha = 1, family = 'binomial')
opt.lambd = glm.train.cv$lambda.min
train.fit.lasso = glmnet(x, y = train$dem, alpha = 1, family = 'binomial')
predict(train.fit.lasso, s = opt.lambd, type = "coefficients")[1:23, ]
然后我在测试数据上测试了模型,得到了可靠的结果(下面,我在测试数据上插入了模型的 ROC 曲线):
在上面使用的训练和测试数据中,我都有响应变量的实际值,并且能够使用该model.matrix()
函数来计算预测值。但是,我有第二部分测试数据,其中响应变量的每个值都是 NA。应用model.matrix()
此数据后,我的矩阵的维度为 0x22:
> dim(x.predict)
[1] 0 22
我尝试了一些替代方法model.matrix()
,但只是得到错误。例如,当我尝试使用 时data.matrix()
,我的矩阵的尺寸是正确的:
> x.predict = data.matrix(predict.data[c(-1,-2,-3, -5,-6, -10, -14, -18,-19, -21, -26,-27, -34,-35,-36,-37)])
> dim(x.predict)
[1] 5010 23
但是,当我尝试使用我的模型估计概率或分类时,我收到以下错误:
> test$test.probs = predict(train.fit.lasso, newx = x.predict, s =opt.lambd, type = "response")
Error in as.matrix(cbind2(1, newx) %*% nbeta) :
error in evaluating the argument 'x' in selecting a method for function 'as.matrix': Error in cbind2(1, newx) %*% nbeta :
Cholmod error 'X and/or Y have wrong dimensions' at file ../MatrixOps/cholmod_sdmult.c, line 90
> test$test.predicts = predict(train.fit.lasso, newx = x.predict[1:5010,], s = opt.lambd, type = "class")
Error in as.matrix(cbind2(1, newx) %*% nbeta) :
error in evaluating the argument 'x' in selecting a method for function 'as.matrix': Error in cbind2(1, newx) %*% nbeta :
Cholmod error 'X and/or Y have wrong dimensions' at file ../MatrixOps/cholmod_sdmult.c, line 90
有人在使用 LASSO 之前遇到过这个问题吗?或者,有人可以帮助我了解.matrix()
LASSO 如何使用不同的函数,以及在响应值为 NA 时计算预测的可能解决方法吗?