glmnet预测方法抛出神秘错误

时间:2013-11-19 21:31:00

标签: r glmnet

我正在尝试使用glmnet进行预测,并获得非常神秘的错误消息。 我在使用glmnet之前没有遇到过这种情况,谷歌搜索错误并不富有成效。最后一行未注释时会发生错误。

library(ISLR)
library(glmnet)


Hitters=na.omit(Hitters)
Hitters$Salary = log(Hitters$Salary)

Hitters.train = Hitters[1:200,]
Hitters.test = Hitters[201:dim(Hitters)[1],]

x=model.matrix(Salary~.,Hitters)[,-1]
cv.out=cv.glmnet(x, Hitters$Salary, alpha=0)
bestlam=cv.out$lambda.min
ridge.mod=glmnet(x, Hitters$Salary, alpha=0,lambda=bestlam)

newx = data.matrix(Hitters.test)
#ridge.pred=predict(ridge.mod,s=bestlam,newx=newx)

错误输出:

Loading required package: Matrix
Loading required package: methods
Loaded glmnet 1.9-5

Error in as.matrix(cbind2(1, newx) %*% nbeta) : 
  error in evaluating the argument 'x' in selecting a method for function 'as.matrix': Error in t(.Call(Csparse_dense_crossprod, y, t(x))) : 
  error in evaluating the argument 'x' in selecting a method for function 't': Error: Cholmod error 'X and/or Y have wrong dimensions' at file ../MatrixOps/cholmod_sdmult.c, line 90
Calls: %*% -> %*% -> t
Calls: predict ... predict.elnet -> NextMethod -> predict.glmnet -> as.matrix
Execution halted

请注意,更改newx = data.matrix(Hitters.test)newx = model.matrix(Salary~.,Hitters.test)没有帮助。

根据要求,这是运行前sessionInfo()的输出。

> sessionInfo()
R version 3.0.2 (2013-09-25)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
[1] C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

以下是运行后的输出:

> sessionInfo()
R version 3.0.2 (2013-09-25)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
[1] C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] glmnet_1.9-5 Matrix_1.1-0 ISLR_1.0

loaded via a namespace (and not attached):
[1] grid_3.0.2      lattice_0.20-23

1 个答案:

答案 0 :(得分:7)

事实证明,我必须NULL回复。以下工作无误:

library(ISLR)
library(glmnet)


Hitters=na.omit(Hitters)
Hitters$Salary = log(Hitters$Salary)

Hitters.train = Hitters[1:200,]
Hitters.test = Hitters[201:dim(Hitters)[1],]

x=model.matrix(Salary~.,Hitters)[,-1]
cv.out=cv.glmnet(x, Hitters$Salary, alpha=0)
bestlam=cv.out$lambda.min
ridge.mod=glmnet(x, Hitters$Salary, alpha=0,lambda=bestlam)

Hitters.test$Salary <- NULL
newx = data.matrix(Hitters.test)
ridge.pred=predict(ridge.mod,s=bestlam,newx=newx)