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

ksk*_*skp 1 r prediction non-linear-regression

我在这里读到的答案很少,但我恐怕无法找到答案.

我的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)
Run Code Online (Sandbox Code Playgroud)

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

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

有人可以提出什么是错的吗?另外,我想知道我是否以正确的方式做到了.

此外,将非常感谢关于如何计算模型精度的一些指示.谢谢!

joe*_*son 7

方案:

lm_colors <- lm(avg_impressions ~ poly(ad_position, 13), data=colors_train_agg)
Run Code Online (Sandbox Code Playgroud)

原因:您可以比较自己如何model.matrix()生成矩阵来对内部数据进行评分predict().因此,当我们通过model(df$var1~df$var2),model.matrix()寻找df$var1df$var2生成矩阵时 - 但这具有训练数据的维度(df).在model和中有不同名称的问题newdata

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

model1 <- lm(var1~var2, data = df)
model2 <- lm(df$var1~df$var2)
debug(predict)
predict(model1, newdata = df1)
predict(model2, newdata = df1) 
Run Code Online (Sandbox Code Playgroud)