【发布时间】:2018-05-30 00:19:37
【问题描述】:
我想使用标记为train 的数据来拟合模型,然后使用标记为test 的数据来预测新值。我想在“many models”场景中执行此操作。
以下是我目前的设置。我的问题是我正在训练并向所有数据添加预测。不知道怎么区分使用modelr
library(modelr)
library(tidyverse)
library(gapminder)
# nest data by continent and label test/train data
nested_gap <- gapminder %>%
mutate(test_train = ifelse(year < 1992, "train", "test")) %>%
group_by(continent) %>%
nest()
# make a linear model function
cont_model <- function(df) {
lm(lifeExp ~ year, data = df)
}
# fit a model and add predictions to all data
fitted_gap <- nested_gap %>%
mutate(model = map(data, cont_model)) %>%
mutate(pred = map2(data, model, add_predictions))
【问题讨论】:
-
在您的
cont_model函数中,添加data = df %>% filter(test_train == "train")以使其仅在适当的时间段内构建lm。 -
@shuckle 谢谢,但是如何使用适合训练数据的模型对测试数据进行预测。
-
lm中的每一个都只适合训练数据。add_predictions步骤将对train和test值进行预测。 -
@shuckle 我想我明白你现在在说什么。由于使用的数据只是训练数据,因此当我将
model和data传递给add_predictions时,我将看到仅基于训练模型的预测。最后一步是仅过滤test观察结果。