【问题标题】:Evaluating linear model with new data returns fitted values使用新数据评估线性模型返回拟合值
【发布时间】:2020-04-26 15:58:16
【问题描述】:

我正在构建和评估我的模型,如下所示。

yData <- rnorm(10)
xData <- matrix(rnorm(20), 10, 2)
polyModel <- lm(yData~polym(xData, degree=2, raw=T))
newData <- matrix(rnorm(100), 50, 2)
yPredicted <- predict(polyModel, polym(newData, degree=2, raw=T))

但是,模型评估 yPredicted 正好等于拟合值 polyModel$fitted.values,一个长度为 10 的向量。在这种情况下,我期望 yPredicted 是一个长度为 50 的向量。一些帮助将不胜感激。

【问题讨论】:

    标签: r lm predict poly


    【解决方案1】:

    predict() 不能很好地工作,除非在 data 参数中指定了数据。这似乎有效:

    polyModel <- lm(yData~poly(V1, V2, degree=2, raw=TRUE),
                    data=as.data.frame(xData))
    length(fitted(polyModel))  ## 10
    newData <- matrix(rnorm(100), 50, 2)
    yPredicted <- predict(polyModel, newdata=as.data.frame(newData))
    length(yPredicted) ## 50
    
    • V1V2 是将矩阵转换为数据框时分配的默认列名。
    • 如果您有未知和/或大量列要放入多项式中(例如 poly(V1, ..., V1000, degree=2, raw=TRUE)),则此规范将无法正常工作

    如果您事先不知道列数, hacky 的解决方案是:

    f <- as.formula(sprintf("yData~poly(%s, degree=2, raw=TRUE)",
               paste("V", seq(ncol(xData)), sep="", collapse=", "))
    polyModel <- lm(f, data=as.frame(xData))
    

    (未经测试)

    【讨论】:

    • 我担心这与此有关。问题是我事先不知道 xData 会有多少列。最大列数为 5。最坏的情况是,我可以进行大小写切换并输入不同的场景 (V1) / (V1, V2) / (V1, V2, V3) ......但我不想.有没有办法将其扩展到 xData 中可变数量的列?
    猜你喜欢
    • 2019-03-12
    • 2020-01-28
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 2018-02-09
    • 2018-10-13
    相关资源
    最近更新 更多