使用 tidymodels 构建与评估模型

R 中的降维

Matt Pickard

Owner, Pickard Predictives, LLC

模型拟合流程

建模第一步:划分数据

R 中的降维

模型拟合流程

建模第二步:准备数据

R 中的降维

模型拟合流程

建模第三步:拟合模型

R 中的降维

模型拟合流程

建模第四步:评估模型

R 中的降维

使用 tidymodels 拟合模型

tidymodels 可将数据划分为训练集与测试集

R 中的降维

使用 tidymodels 拟合模型

tidymodels 的 recipe 提供预处理步骤函数

R 中的降维

使用 tidymodels 拟合模型

tidymodels 可在工作流中拟合多种模型

R 中的降维

划分训练集与测试集

split <- initial_split(credit_df, prop = 0.8, strata = credit_score)


train <- split %>% training()
test <- split %>% testing()
R 中的降维

创建 recipe 和模型

feature_selection_recipe <- 
  recipe(credit_score ~ ., data = train) %>%

step_filter_missing(all_predictors(), threshold = 0.5) %>%
step_scale(all_numeric_predictors()) %>%
step_nzv(all_predictors()) %>%
prep()
lr_model <- logistic_reg() %>%

set_engine("glm")
R 中的降维

创建并拟合工作流

credit_wflow <- workflow() %>%

add_recipe(feature_selection_recipe) %>%
add_model(lr_model)
credit_fit <- credit_wflow %>% fit(data = train)
R 中的降维

评估模型

# 预测测试集
credit_pred_df <- predict(credit_fit, test) %>% 
  bind_cols(test %>% select(credit_score))


# 评估 F 分数 f_meas(credit_pred_df, credit_score, .pred_class)
# A tibble: 1 × 3
  .metric .estimator .estimate
  <chr>   <chr>          <dbl>
1 f_meas  macro          0.519
R 中的降维

用 tidy() 查看 recipe

tidy(feature_selection_recipe, number = 1)
# A tibble: 2 × 2
  terms            id                  
  <chr>            <chr>               
1 age              filter_missing_gVVfc
2 outstanding_debt filter_missing_gVVfc
R 中的降维

用 tidy() 查看模型

# 显示模型估计
tidy(credit_fit)
# A tibble: 44 × 5
   term                estimate std.error statistic p.value
   <chr>                  <dbl>     <dbl>     <dbl>   <dbl>
 1 (Intercept)           2.88       0.918    3.13   0.00173
 2 monthAugust          -0.449      0.236   -1.91   0.0565 
 3 monthFebruary        17.7      677.       0.0262 0.979  
 4 monthJanuary         17.7      661.       0.0268 0.979  
 ...                    ...       ...        ...    ... 
R 中的降维

让我们来练习!

R 中的降维

Preparing Video For Download...