【问题标题】:Lasso error in glmnet NA/NaN/Infglmnet NA/NaN/Inf 中的套索错误
【发布时间】:2023-03-05 20:15:01
【问题描述】:

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

非常感谢大家!

【问题讨论】:

    标签: r glmnet lasso-regression


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      当您尝试匹配两个或更多不相等的矩阵行以构建模型或其他内容时,会出现此错误。

      您可以通过从数据集中删除 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#
      

      【讨论】:

        猜你喜欢
        • 2014-03-18
        • 1970-01-01
        • 2018-07-03
        • 1970-01-01
        • 2020-07-24
        • 2019-05-12
        • 2017-05-03
        • 2013-10-24
        • 2019-04-04
        相关资源
        最近更新 更多