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

2023-09-03 13:37:09 作者:别看有些人表面挺丧的,其实背后也有偷偷在努力生活。今日小编为

我在这里读到的关于这个问题的答案很少,但恐怕我还无法找到答案。

我的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)
第二篇 介绍Python中关键字 变量 注释 模块

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

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)