在 中实现的数据科学 (TM) 的整洁模型中modelr
,重新采样的数据使用list-columns进行组织:
library(modelr)
library(tidyverse)
# create the k-folds
df_heights_resampled = heights %>%
crossv_kfold(k = 10, id = "Resample ID")
可以对map
list-column 中的每个训练数据集建立模型,并通过ping list-columntrain
来计算性能指标。map
test
如果需要对多个模型执行此操作,则需要对每个模型重复此操作。
# create a list of formulas
formulas_heights = formulas(
.response = ~ income,
model1 = ~ height + weight + marital + sex,
model2 = ~ height + weight + marital + sex + education
)
# fit each of the models in the list of formulas
df_heights_resampled = df_heights_resampled %>%
mutate(
model1 = map(train, function(train_data) {
lm(formulas_heights[[1]], data = train_data)
}),
model2 = map(train, function(train_data) {
lm(formulas_heights[[2]], data = train_data)
})
)
# score the models on the test sets
df_heights_resampled = df_heights_resampled %>%
mutate(
rmse1 = map2_dbl(.x = model1, .y = test, .f = rmse),
rmse2 = map2_dbl(.x = model2, .y = test, .f = rmse)
)
这使:
> df_heights_resampled
# A tibble: 10 × 7
train test `Resample ID` model1 model2 rmse1 rmse2
<list> <list> <chr> <list> <list> <dbl> <dbl>
1 <S3: resample> <S3: resample> 01 <S3: lm> <S3: lm> 58018.35 53903.99
2 <S3: resample> <S3: resample> 02 <S3: lm> <S3: lm> 55117.37 50279.38
3 <S3: resample> <S3: resample> 03 <S3: lm> <S3: lm> 49005.82 44613.93
4 <S3: resample> <S3: resample> 04 <S3: lm> <S3: lm> 55437.07 51068.90
5 <S3: resample> <S3: resample> 05 <S3: lm> <S3: lm> 48845.35 44673.88
6 <S3: resample> <S3: resample> 06 <S3: lm> <S3: lm> 58226.69 54010.50
7 <S3: resample> <S3: resample> 07 <S3: lm> <S3: lm> 56571.93 53322.41
8 <S3: resample> <S3: resample> 08 <S3: lm> <S3: lm> 46084.82 42294.50
9 <S3: resample> <S3: resample> 09 <S3: lm> <S3: lm> 59762.22 54814.55
10 <S3: resample> <S3: resample> 10 <S3: lm> <S3: lm> 45328.48 41882.79
问题:
如果要探索的模型数量很大,这会很快变得很麻烦。modelr
提供fit_with
允许迭代多个模型(以多个公式为特征)但似乎不允许像train
上面的模型中那样的列表列的函数。我假设其中一个*map*
函数系列可以实现这一点(invoke_map
?),但无法弄清楚如何。