【问题标题】:many models grouped modelr::add_predictions许多模型分组 modelr::add_predictions
【发布时间】: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 %&gt;% filter(test_train == "train") 以使其仅在适当的时间段内构建 lm。
  • @shuckle 谢谢,但是如何使用适合训练数据的模型对测试数据进行预测。
  • lm 中的每一个都只适合训练数据。 add_predictions 步骤将对 train 和 test 值进行预测。
  • @shuckle 我想我明白你现在在说什么。由于使用的数据只是训练数据,因此当我将model 和data 传递给add_predictions 时,我将看到仅基于训练模型的预测。最后一步是仅过滤 test 观察结果。

标签: r tidyverse


【解决方案1】:

这是@shuckle提供的解决方案

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 than only trains on training set
cont_model <- function(df) {
  lm(lifeExp ~ year, data = df %>% filter(test_train == "train"))
}

# 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))

# unnest predictions and filter only the test rows
fitted_gap %>% 
  unnest(pred) %>% 
  filter(test_train == "test")

【讨论】:

    猜你喜欢
    • 2017-07-02
    • 2017-03-05
    • 1970-01-01
    • 2017-01-17
    • 2020-09-24
    • 2019-06-21
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    相关资源
    最近更新 更多