如何使用 tidymodels 在折叠的每个火车部分训练的每个交叉验证折叠中应用预处理?

问题描述 投票:0回答:0

我尝试将 tidymodels R 包用于 ml 管道。我可以在训练数据上定义一个预处理管道(配方)并将其应用于我的交叉验证的每个重新采样。但这使用(全局)训练数据来预处理折叠。我认为比较正确的是在折叠的每个“分析”(即训练)部分定义一个预处理方法,并将其应用于折叠的“评估”(即测试)部分。

以下代码给出了我的问题的示例:

library(tidyverse)
library(tidymodels)

set.seed(1000)

mtcars = mtcars |> select(mpg, hp)
init_split <- initial_split(mtcars, prop = 0.9)

preprocessing_recipe <- recipe(mpg ~ hp,
                           data = training(init_split)
) |>
step_normalize(all_predictors())
preprocessing_recipe = preprocessing_recipe %>% prep()
preprocessing_recipe

cv_folds <-  bake(preprocessing_recipe, new_data = training(init_split)) %>%
vfold_cv(v = 3)

## these resamples are not properly scaled:

training(cv_folds$splits[[1]]) %>% lapply(mean)

## $hp
## [1] 0.1442218

training(cv_folds$splits[[1]]) %>% lapply(sd)

## $hp
## [1] 1.167365

## while the preprocessing on the training data leads to exactly scaled data:

preprocessing_recipe$template %>% lapply(mean)

## $hp
## [1] -1.249001e-16

preprocessing_recipe$template %>% lapply(sd)

## $hp
## [1] 1

上面失败的原因很清楚。但是,我如何才能(高效、优雅地)更改上述管道以在折叠的每个火车部分定义一个配方并将其应用于测试部分?在我看来,这是避免数据泄漏的方法。我没有在任何帖子的文档中找到任何提示。谢谢!

r resampling tidymodels
© www.soinside.com 2019 - 2024. All rights reserved.