glmnet中Lasso错误NA/NaN/Inf

11

我在使用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"

我可以使用“鸢尾花”数据集重现以下错误,但这里是适用于我的特定数据的简化代码:

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

这是一件你可以轻松复制的事情:

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)

非常感谢大家!

2个回答

14

使用as.matrix会将数字值强制转换为字符类型,因为它会保留"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"

通常使用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

0

当你尝试匹配两个或多个不相等的矩阵行来构建模型或其他操作时,会出现此错误。

您可以通过从数据集中删除NA单元格并检查维度的相等性来解决此问题。对于构建模型矩阵,必须仔细指导训练和测试数据集。

请尝试以下代码:

z <- data[complete.cases(data), ] # For choosing cases without missed items#

I = sample(size =  round(nrow(z)/7,0),x =  1:nrow(z), replace = F) # Sampling from original data to construct test and train sets#

Datatrain = z[I,] #Introducing train set#
Datatest = z[-I,] #Introducing test set#

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接