運用領域知識建立新特徵

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 流程:載入資料、宣告模型、切分資料、建立 recipe、封裝成 workflow、擬合並評估效能。

可至 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 的特徵工程

建置工作流程

將模型與 recipe 封裝成 workflow 物件。

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

擬合 workflow

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 的特徵工程

一起來練習吧!

R 的特徵工程

Preparing Video For Download...