r - 许多模型分组 modelr::add_predictions
问题描述
我想使用标记为的数据train
来拟合模型,然后使用标记为的数据test
来预测新值。我想在“许多模型”场景中执行此操作。
以下是我目前的设置。我的问题是我正在训练并向所有数据添加预测。我不知道如何区分使用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))
解决方案
这是@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")
推荐阅读
- static-libraries - 如何为 obj c 静态库创建 xcframework?
- json - 从独立脚本查询 DatoCMS graphQL API。获取字段 [myModelName] 在“查询”类型上不存在
- php - 在浏览器中显示 RasberryPi3 php var_dump 的问题
- spring-boot - 如何在 SpringBoot RestTemplate 中发送 json 请求正文和请求标头
- microservices - 事件溯源和领域事件
- flutter - 你可以在 sqflite 颤振中存储嵌套地图吗
- python - 使用 BERT 模型进行文本分类
- java - 如何根据按钮的数量使按钮成为动态的?
- python - # Buildozer 执行最后一条命令失败(错误)
- java - 原始数组的 Java toArray() 转换