利用领域知识创建新特征

R 中的特征工程

Jorge Zazueta

Research Professor and Head of the Modeling Group at the School of Economics, UASLP

领域知识的重要性

领域知识可帮助我们为特定模型或任务识别并创建相关、有效的特征。

特征工程旨在由现有变量构造新的输入特征。

领域知识示例:

  • 金融:破产的关键决定因素
  • 医疗:与特定治疗相关的既往病史
  • 营销:区分某消费群体的特征
R 中的特征工程

基于专业经验创建变量

我们希望基于以下特征向量预测酒店是否会被取消:

features <- 
c("IsCanceled", "LeadTime",
  "arrival_date",
  "StaysInWeekendNights",
  "StaysInWeekNights",
  "PreviousCancellations",
  "PreviousBookingsNotCanceled",
  "ReservedRoomType",
  "AssignedRoomType","BookingChanges",
  "DepositType","CustomerType",
  "ADR","TotalOfSpecialRequests")

原始数据中的特征

可从 arrival_date 生成有用特征。

到达日期可分解为星期、周、月和节假日

但手动处理很快会变繁琐,需要自动化!

R 中的特征工程

tidymodels 框架

我们将使用基于 tidymodels 的工作流。它是遵循 tidyverse 原则(1)的建模与机器学习包集合,重点在特征工程。

简化的 tidymodels 工作流:加载数据、声明模型、划分数据、设置配方、打包为工作流、拟合并评估性能。

可在 www.tidymodels.org 了解更多

1 [Tidyverse 指导原则。](https://design.tidyverse.org/unifying-principles.html)
R 中的特征工程

为分析准备数据

先准备数据。

cancelations <- 
  cancelations %>% 
  mutate(across(where(is_character),as.factor))
set.seed(123)
split <- cancellations %>% 
    initial_split(
    strata = "IsCanceled")
train <- training(split)
test <- testing(split)

可用 prop 参数调整训练/测试划分(默认 3/4)。

initial_split(data, prop = 3/4, strata = NULL)

验证 traintest 在取消预订比例上相近。

train %>% 
  select(IsCanceled) %>% table() %>% 
  prop.table()

IsCanceled
        0         1 
0.5826946 0.4173054
test %>% 
  select(IsCanceled) %>% table() %>% 
  prop.table()

IsCanceled
        0         1 
0.5827788 0.4172212
R 中的特征工程

构建工作流

声明模型

lr_model <- logistic_reg()

构建配方(recipe)

lr_recipe <- 
  recipe(IsCanceled ~., data = train) %>%
  update_role(Agent, new_role = "ID" ) %>%
  step_date(arrival_date, 
      features = c("dow", "week", "month")) %>%
  step_holiday(arrival_date, 
      holidays = timeDate::listHolidays("US")) %>%
  step_rm(arrival_date) %>%
  step_dummy(all_nominal_predictors())

打印 lr_recipe

Recipe
Inputs:

      role #variables
        ID          1
   outcome          1
 predictor         13

Operations:

Date features from arrival_date
Holiday features from arrival_date
Variables removed arrival_date
Dummy variables from all_nominal_predictors()
R 中的特征工程

构建工作流

将模型与配方打包为 workflow 对象。

lr_workflow <- 
  workflow()%>%
  add_model(lr_model)%>%
  add_recipe(lr_recipe)

拟合工作流

lr_fit <- 
  lr_workflow %>%
  fit(data = train)
R 中的特征工程

构建工作流

使用 tidy(lr_fit) 可汇总模型。

# A tibble: 65 × 5
   term                        estimate std.error statistic   p.value
   <chr>                          <dbl>     <dbl>     <dbl>     <dbl>
 1 (Intercept)                 -1.92     0.228        -8.43 3.57e- 17
 2 LeadTime                     0.00414  0.000268     15.4  1.16e- 53
 3 StaysInWeekendNights         0.0860   0.0382        2.25 2.45e-  2
 4 StaysInWeekNights            0.0804   0.0185        4.34 1.40e-  5
 5 PreviousCancellations        2.39     0.147        16.2  2.45e- 59
 6 PreviousBookingsNotCanceled -0.440    0.0450       -9.77 1.45e- 22
 7 BookingChanges              -0.449    0.0463       -9.69 3.18e- 22
 8 ADR                          0.0104   0.000782     13.2  4.85e- 40
 9 TotalOfSpecialRequests      -0.727    0.0316      -23.0  5.29e-117
10 arrival_date_week            0.0245   0.0171        1.43 1.53e-  1
# … with 55 more rows
# ℹ Use `print(n = ...)` to see more rows
R 中的特征工程

评估模型性能

现在评估模型性能。

lr_aug <- lr_fit %>% augment(test)

bind_rows(
  lr_aug %>% 
  roc_auc(truth = IsCanceled,.pred_0),
  lr_aug %>% 
  accuracy(truth = IsCanceled,.pred_class))
# A tibble: 2 × 3
  .metric  .estimator .estimate
  <chr>    <chr>          <dbl>
1 roc_auc  binary         0.842
2 accuracy binary         0.782
lr_aug %>%
  roc_curve(truth = IsCanceled, .pred_0) %>%
  autoplot()

我们模型的ROC曲线。

R 中的特征工程

Vamos praticar!

R 中的特征工程

Preparing Video For Download...