当newdata具有较少级别时,R predict.glm

时间:2016-08-28 18:03:09

标签: r regression glm predict

predict()的标签和级别(因子级别的基础整数)与列车数据的标签和级别不匹配时,我试图向自己证明newdata不会给出错误的预测。 / p>

我想我确实证明了这一点,而且我正在分享下面的代码,但我想问一下,在预测newdata时,R究竟在做什么。我知道它没有将newdata附加到训练数据上,是否会在预测之前将newdata的因子标签转换为相应的列车数据表示?

options(stringsAsFactors = TRUE)
dat <- data.frame(x = rep(c("cat", "dog", "bird", "horse"), 100), y = rgamma(100, shape=3,  scale = 300))
model <- glm(y~., family = Gamma(link = "log"), data = dat)

coefficients(model)
# (Intercept)        xcat        xdog      xhorse 
#   6.5816536   0.2924488   0.3586094   0.2740487 

newdata1 <- data.frame(x = "cat")
newdata2 <- data.frame(x = "bird")
newdata3 <- data.frame(x = "dog")

predict.glm(object = model, newdata = newdata1, type = "response")
#       1 
# 966.907 
exp(6.5816536 + 0.2924488) #intercept + cat coef
# [1] 966.9071

predict.glm(object = model, newdata = newdata2, type = "response")
#        1 
# 721.7318 
exp(6.5816536)
# [1] 721.7318

predict.glm(object = model, newdata = newdata3, type = "response")
#        1 
# 1033.042 
exp(6.5816536 + 0.3586094)
# [1] 1033.042

unclass(dat$x)
#  [1] 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3
# [87] 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4
# [173] 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3
# [259] 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4
# [345] 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4 2 3 1 4
# attr(,"levels")
# [1] "bird"  "cat"   "dog"   "horse"

unclass(newdata1$x)
# [1] 1
# attr(,"levels")
# [1] "cat"

unclass(newdata2$x)
# [1] 1
# attr(,"levels")
# [1] "bird"

1 个答案:

答案 0 :(得分:3)

模型对象具有用于模型估计的xlevels记录因子级别。对于您的示例,我们有:

model$xlevels
#$x
#[1] "bird"  "cat"   "dog"   "horse"

当您的新数据以预测方式显示时,系数会匹配。例如,您的newdata1将匹配&#34; cat&#34;级别,这是xlevels中的第二级。因此,预测将很难找到该级别的正确系数。