在 R 中使用 tidymodels 建模
David Svancer
Data Scientist

定义列角色
确定变量类型
使用 recipe() 函数完成

添加所需的预处理步骤
每个步骤用唯一的 step_*() 函数添加

recipe 对象基于数据源训练,通常是训练集
使用 prep() 函数训练配方

将所有已训练的预处理变换应用于:
使用 bake() 函数应用配方

对潜在客户评分数据的 total_time 做对数变换
leads_training
# A tibble: 996 x 7
purchased total_visits total_time pages_per_visit total_clicks lead_source us_location
<fct> <dbl> <dbl> <dbl> <dbl> <fct> <fct>
1 yes 7 1148 7 59 direct_traffic west
2 no 5 228 2.5 25 email southeast
3 no 7 481 2.33 21 organic_search west
4 no 4 177 4 37 direct_traffic west
5 no 2 1273 2 26 email midwest
# ... with 991 more rows
recipe() 函数
data 参数
将 recipe 对象传给 step_log(),添加对数变换步骤
total_time,并指定对数底数leads_log_rec <- recipe(purchased ~ ., data = leads_training) %>%step_log(total_time, base = 10)
leads_log_rec
Data Recipe
Inputs:
role #variables
outcome 1
predictor 6
Operations:
Log transformation on total_time
将 recipe 对象传给 summary()
type 列role 列leads_log_rec %>%
summary()
# A tibble: 7 x 4
variable type role source
<chr> <chr> <chr> <chr>
1 total_visits numeric predictor original
2 total_time numeric predictor original
3 pages_per_visit numeric predictor original
4 total_clicks numeric predictor original
5 lead_source nominal predictor original
6 us_location nominal predictor original
7 purchased nominal outcome original
prep() 函数
recipe 对象training 参数
打印已训练的 recipe 对象
[trained] 标记leads_log_rec_prep <- leads_log_rec %>%
prep(training = leads_training)
leads_log_rec_prep
Data Recipe
Inputs:
role #variables
outcome 1
predictor 6
Training data contained 996 data points and
no missing data.
Operations:
Log transformation on total_time [trained]
bake() 函数
recipe 对象new_data 参数leads_training 用于训练该配方prep() 会保留转换后的数据new_data 传入 NULL 可提取leads_log_rec_prep %>%
bake(new_data = NULL)
# A tibble: 996 x 7
total_visits total_time ... us_location purchased
<dbl> <dbl> ... <fct> <fct>
1 7 3.06 ... west yes
2 5 2.36 ... southeast no
3 7 2.68 ... west no
4 4 2.25 ... west no
5 2 3.10 ... midwest no
# ... with 991 more rows
转换未用于配方训练的数据集
new_data 参数leads_log_rec_prep %>%
bake(new_data = leads_test)
# A tibble: 332 x 7
total_visits total_time ... us_location purchased
<dbl> <dbl> ... <fct> <fct>
1 8 2 ... west no
2 4 3.13 ... northeast yes
3 3 2.25 ... west no
4 2 1.20 ... midwest no
5 9 3.01 ... west yes
# ... with 327 more rows
在 R 中使用 tidymodels 建模