glmnet NA/NaN/Inf中的套索错误

Jas*_*son 10 r lasso-regression glmnet

我遇到了glmnet的问题,因为我不断收到错误消息

"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"
Run Code Online (Sandbox Code Playgroud)

下面我可以使用'iris'数据集复制错误,但这里是我的特定数据的简化代码:

vars <- as.matrix(ind.vars)
lasso <- glmnet(vars, y=cup98$TARGET_D, alpha=1)
Run Code Online (Sandbox Code Playgroud)

以下是您可以轻松复制的内容:

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)
Run Code Online (Sandbox Code Playgroud)

非常感谢大家!

42-*_*42- 12

随着 as.matrix因为你留下"物种"你是强迫的数值为字符:

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"
Run Code Online (Sandbox Code Playgroud)

也通常是一个非常糟糕的主意,用attach/detach的,如果你不知道为什么你不应该使用它,那么你 绝对应该使用它.

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
Run Code Online (Sandbox Code Playgroud)