如果你有来自这两个包的功能会有所帮助:dplyr
和tidyr
. 以下代码向您展示了如何按国家/地区训练多个模型:
library(dplyr)
library(tidyr)
df <- gapminder::gapminder
by_country <-
df %>%
nest(data = -c(continent, country)) %>%
mutate(model = lapply(data, learn))
请注意,这learn
是一个将单个数据帧作为输入的函数。稍后我将向您展示如何定义该函数。现在您需要知道从该管道返回的数据帧如下:
# A tibble: 142 x 4
country continent data model
<fct> <fct> <list> <list>
1 Afghanistan Asia <tibble [12 x 4]> <LrnrRgrR>
2 Albania Europe <tibble [12 x 4]> <LrnrRgrR>
3 Algeria Africa <tibble [12 x 4]> <LrnrRgrR>
4 Angola Africa <tibble [12 x 4]> <LrnrRgrR>
5 Argentina Americas <tibble [12 x 4]> <LrnrRgrR>
6 Australia Oceania <tibble [12 x 4]> <LrnrRgrR>
7 Austria Europe <tibble [12 x 4]> <LrnrRgrR>
8 Bahrain Asia <tibble [12 x 4]> <LrnrRgrR>
9 Bangladesh Asia <tibble [12 x 4]> <LrnrRgrR>
10 Belgium Europe <tibble [12 x 4]> <LrnrRgrR>
要定义learn
函数,我按照mlr3网站上提供的步骤进行操作。功能是
learn <- function(df) {
# I create a regression task as the target `lifeExp` is a numeric variable.
task <- mlr3::TaskRegr$new(id = "gapminder", backend = df, target = "lifeExp")
# define the learner you want to use.
learner <- mlr3::lrn("regr.rpart")
# train your dataset and return the trained model as an output
learner$train(task)
}
我希望这能解决你的问题。
新的
考虑以下步骤来训练您的模型并预测每个国家/地区的结果。
create_task <- function(id, df, ratio) {
train <- sample(nrow(df), ratio * nrow(df))
task <- mlr3::TaskRegr$new(id = as.character(id), backend = df, target = "lifeExp")
list(task = task, train = train, test = seq_len(nrow(df))[-train])
}
model_task <- function(learner, task_list) {
learner$train(task_list[["task"]], row_ids = task_list[["train"]])
}
predict_result <- function(learner, task_list) {
learner$predict(task_list[["task"]], row_ids = task_list[["test"]])
}
by_country <-
df %>%
nest(data = -c(continent, country)) %>%
mutate(
task_list = Map(create_task, country, data, 0.8),
learner = list(mlr3::lrn("regr.rpart"))
) %>%
within({
Map(model_task, learner, task_list)
prediction <- Map(predict_result, learner, task_list)
})