gpt4 book ai didi

r - glmnet 预测方法抛出神秘错误

转载 作者:行者123 更新时间:2023-12-02 03:07:09 34 4
gpt4 key购买 nike

我尝试使用 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

最佳答案

事实证明,我必须 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)

关于r - glmnet 预测方法抛出神秘错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20082484/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com