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

时间:2014-02-07 18:48:35

标签: r glmnet lasso

我遇到了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"

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

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 个答案:

答案 0 :(得分: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"

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

答案 1 :(得分: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#