【问题标题】:predic.lm gives wrong number of predicted values when I fit and predict a model using a matrix variable当我使用矩阵变量拟合和预测模型时,predic.lm 给出错误数量的预测值
【发布时间】:2019-02-13 03:24:49
【问题描述】:

过去我使用lm 函数与matrix-type 数据和data.frame-type。但我想这是我第一次尝试使用没有data.frame 的模型来使用predict。而且我不知道如何使它工作。

我阅读了一些其他问题(例如Getting Warning: " 'newdata' had 1 row but variables found have 32 rows" on predict.lm),我很确定我的问题与拟合模型后得到的系数名称有关。由于某种原因,系数名称是矩阵名称与列名称的粘贴......我一直无法找到解决方法......

library(tidyverse)
library(MASS)

set.seed(1)
label <- sample(c(T,F), nrow(Boston), replace = T, prob = c(.6,.4))

x.train <- Boston %>% dplyr::filter(., label) %>%
  dplyr::select(-medv) %>% as.matrix()
y.train <- Boston %>% dplyr::filter(., label) %>%
  dplyr::select(medv) %>% as.matrix()
x.test <- Boston %>% dplyr::filter(., !label) %>%
  dplyr::select(-medv) %>% as.matrix()
y.test <- Boston %>% dplyr::filter(., !label) %>%
  dplyr::select(medv) %>% as.matrix()

fit_lm <- lm(y.train ~ x.train)
fit_lm2 <- lm(medv ~ ., data = Boston, subset = label)
predict(object = fit_lm, newdata = x.test %>% as.data.frame()) %>% length() 
predict(object = fit_lm2, newdata = x.test %>% as.data.frame()) %>% length()
# they get different numbers of predicted data
# the first one gets a number a results consistent with x.train

欢迎任何帮助。

【问题讨论】:

    标签: r regression linear-regression prediction lm


    【解决方案1】:

    我无法修复您的 tidyverse 代码,因为我不使用此软件包。但我能够解释为什么predict 在第一种情况下会失败。

    让我使用内置数据集trees 进行演示:

    head(trees, 2)
    #  Girth Height Volume
    #1   8.3     70   10.3
    #2   8.6     65   10.3
    

    lm的正常使用方式是

    fit <- lm(Girth ~ ., trees)
    

    变量名(在~的右轴)是

    attr(terms(fit), "term.labels")
    #[1] "Height" "Volume"
    

    使用predict时需要在newdata中提供这些变量。

    predict(fit, newdata = data.frame(Height = 1, Volume = 2))
    #       1 
    #11.16125 
    

    现在,如果您使用矩阵拟合模型:

    X <- as.matrix(trees[2:3])
    y <- trees[[1]]
    fit2 <- lm(y ~ X)
    attr(terms(fit2), "term.labels")
    #[1] "X"
    

    您需要在newdata 中为predict 提供的变量现在是X,而不是HeightGirth。请注意,由于X 是一个矩阵变量,因此在将其提供给数据框时需要使用I() 对其进行保护。

    newdat <- data.frame(X = I(cbind(1, 2)))
    str(newdat)
    #'data.frame':  1 obs. of  1 variable:
    # $ X: AsIs [1, 1:2] 1 2
    
    predict(fit2, newdat)
    #       1 
    #11.16125 
    

    cbind(1, 2) 没有列名并不重要。重要的是这个矩阵在newdat中被命名为X

    【讨论】:

      猜你喜欢
      • 2015-10-31
      • 2019-08-08
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 2017-09-05
      相关资源
      最近更新 更多