Lasso error in glmnet NA/NaN/Inf

北战南征 提交于 2019-12-08 15:55:19

问题


I'm having an issue with glmnet in that I keep getting the error message

"Error in elnet(x, is.sparse, ix, jx, y, weights, offset, type.gaussian,  : NA/NaN/Inf in foreign function call (arg 5)
In addition: Warning message:
In elnet(x, is.sparse, ix, jx, y, weights, offset, type.gaussian,  : NAs introduced by coercion"

Below I can replicate the error with the 'iris' data set, but here is the simplified code for my particular data:

vars <- as.matrix(ind.vars)
lasso <- glmnet(vars, y=cup98$TARGET_D, alpha=1)

Here is something you can easily reproduce:

data(iris)
attach(iris)
x <- as.matrix(data.frame(Sepal.Width, Petal.Length, Petal.Width, Species))
y <- Sepal.Length
lasso <- glmnet(x,y=y, alpha=1)

Thanks a lot everybody!


回答1:


With as.matrix you are coercing the numeric values to character because you are leaving in "Species":

str(as.matrix(iris[, c('Sepal.Width', 'Petal.Length', 'Petal.Width', 'Species')]))
 chr [1:150, 1:4] "3.5" "3.0" "3.2" "3.1" "3.6" "3.9" ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"

Also usually a very bad idea to use attach/detach, and if you do not know why you should not use it, then you most definitely should not use it.

data(iris); require(glmnet)
x<-as.matrix(iris[, c('Sepal.Width', 'Petal.Length', 'Petal.Width')])
y<-iris$Sepal.Length
lasso<-glmnet(x,y=y, alpha=1); lasso   # no error


来源:https://stackoverflow.com/questions/21635508/lasso-error-in-glmnet-na-nan-inf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!