R 警告:newdata' 有 15 行,但找到的变量有 22 行

R Warning: newdata' had 15 rows but variables found have 22 rows

我在这里阅读了一些关于此的答案,但恐怕我无法找出答案。

我的 R 代码是:

colors <- bmw[bmw$Channel=="Colors" & bmw$Hour=20,]
colors_test <- tail(colors, 89)
colors_train <- head(colors, 810)

colors_train_agg <- aggregate(colors_train$Impressions, list(colors_train$`Position of Ad in Break`), FUN=mean, na.rm=TRUE)
colnames(colors_train_agg) <- c("ad_position", "avg_impressions")
lm_colors <- lm(colors_train_agg$avg_impressions ~ poly(colors_train_agg$ad_position, 12))
 summary(lm_colors)

colors_test_agg <- aggregate(colors_test$Impressions, list(colors_test$`Position of Ad in Break`), FUN=mean, na.rm=TRUE)
colnames(colors_test_agg) <- c("ad_position", "avg_impressions")
new.df <- data.frame(colors_test_agg$ad_position)
colnames(new.df) <- c("ad_position")
colors_test_test <- predict(lm_colors, newdata=new.df)

所以我的训练数据和测试数据的列名完全相同。我仍然收到警告:

Warning message: 'newdata' had 15 rows but variables found have 22 rows

有人能指出哪里出了问题吗?另外,我想知道我的做法是否正确。

此外,将不胜感激有关如何计算模型准确性的一些指示。谢谢!

解决方案:

lm_colors <- lm(avg_impressions ~ poly(ad_position, 13), data=colors_train_agg)

原因: 大家可以自己比较一下model.matrix()是如何生成矩阵对predict()里面的数据进行评分的。因此,当我们传递 model(df$var1~df$var2) 时,model.matrix() 会寻找 df$var1df$var2 来生成矩阵——但这具有训练数据 (df) 的维度。在 modelnewdata

中使用不同名称的问题

完成以下步骤(如果您有兴趣了解原因):

model1 <- lm(var1~var2, data = df)
model2 <- lm(df$var1~df$var2)
debug(predict)
predict(model1, newdata = df1)
predict(model2, newdata = df1)