代码之家  ›  专栏  ›  技术社区  ›  Alex

许多模型分组建模器::添加预测

  •  0
  • Alex  · 技术社区  · 8 年前

    我想使用标记为 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))
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Alex    8 年前

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