首页 文章

glm`prepected()`错误:没有适用于'predict'的方法应用于类“list”的对象

提问于
浏览
1

我在控制输入预测函数的对象类型时遇到问题 . 这是我生成 glm 对象的简化函数 .

fitOneSample <- function(x,data,sampleSet)
{
  #how big of a set are we going to analyze? Pick a number between 5,000 & 30,000, then select that many rows to study
  sampleIndices <- 1:5000

  #now randomly pick which columns to study
  colIndices <- 1:10

  xnames <- paste(names(data[,colIndices]),sep = "")
  formula <- as.formula(paste("target ~ ", paste(xnames,collapse = "+")))
  glm(formula,family=binomial(link=logit),data[sampleIndices,])
}

myFit <- fitOneSample(1,data,sampleSet)
fits <- sapply(1:2,fitOneSample,data,sampleSet)
all.equal(myFit,fits[,1]) #different object types

#this works
probability <- predict(myFit,newdata = data)

#this doesn't
probability2 <- predict(fits[,1],newdata = data)
# Error in UseMethod("predict") :
# no applicable method for 'predict' applied to an object of class "list"

如何访问 fits[,1] 中的列,以便我可以使用预测函数获得与 myFit 相同的结果?

1 回答

  • 1

    我想我现在能够恢复你的状况了 .

    fits <- sapply(names(trees),
                   function (y) do.call(lm, list(formula = paste0(y, " ~ ."), data = trees)))
    

    这使用内置数据集 trees 作为示例,拟合三个线性模型:

    Girth ~ Height + Volume
    Height ~ Girth + Volume
    Volume ~ Height + Girth
    

    由于我们使用了 sapply ,并且每次迭代都返回相同的 lm 对象或长度为12的列表,因此结果将简化为 12 * 3 矩阵:

    class(fits)
    # "matrix"
    
    dim(fits)
    # 12  3
    

    矩阵索引 fits[, 1] 有效 .

    如果你检查 str(fits[, 1]) ,它几乎看起来像一个普通的 lm 对象 . 但如果你进一步检查:

    class(fits[, 1])
    # "list"
    

    Em? It does not have "lm" class! 因此,当您调用泛型函数 predict 时, S3 dispatch方法将失败:

    predict(x)
    #Error in UseMethod("predict") : 
    #  no applicable method for 'predict' applied to an object of class "list"
    

    This can be seen as a good example that sapply is destructive. 我们想要 lapply ,或者至少是 sapply(..., simplify = FALSE)

    fits <- lapply(names(trees),
                   function (y) do.call(lm, list(formula = paste0(y, " ~ ."), data = trees)))
    

    lapply 的结果更容易理解 . 它是一个长度为3的列表,其中每个元素都是 lm 对象 . 我们可以通过 fits[[1]] 访问第一个模型 . 现在一切都会奏效:

    class(fits[[1]])
    # "lm"
    
    predict(fits[[1]])
    #        1         2         3         4         5         6         7         8 
    # 9.642878  9.870295  9.941744 10.742507 10.801587 10.886282 10.859264 10.957380 
    #        9        10        11        12        13        14        15        16 
    #11.588754 11.289186 11.946525 11.458400 11.536472 11.835338 11.133042 11.783583 
    #       17        18        19        20        21        22        23        24 
    #13.547349 12.252715 12.603162 12.765403 14.002360 13.364889 14.535617 15.016944 
    #       25        26        27        28        29        30        31 
    #15.628799 17.945166 17.958236 18.556671 17.229448 17.131858 21.888147
    

    你可以修改你的代码

    fits <- lapply(1:2,fitOneSample,data,sampleSet)
    probability2 <-predict(fits[[1]],newdata = data)
    

相关问题