為什麼要轉換既有特徵?

R 的特徵工程

Jorge Zazueta

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

讓模型更省力

透過讓資料更好處理,可以提升機器學習模型的效能。

glimpse(loans_num)
Rows: 614
Columns: 6
$ Loan_Status       <fct> Y, N, Y, Y, Y, Y, Y, N, Y, N, Y, Y, Y, N...
$ ApplicantIncome   <dbl> 5849, 4583, 3000, 2583, 6000, 5417, 233...
$ CoapplicantIncome <dbl> 0, 1508, 0, 2358, 0, 4196, 1516, 2504, 1...
$ LoanAmount        <dbl> NA, 128, 66, 120, 141, 267, 95, 158, 168...
$ Loan_Amount_Term  <dbl> 360, 360, 360, 360, 360, 360, 360, 360, ...
$ Credit_History    <fct> 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1...
R 的特徵工程

對數轉換(Log transformation)

對數(log)轉換數值特徵可:

  • 處理偏態資料
  • 降低離群值影響
  • 將乘法關係轉為加法
  • 讓資料更適合建模
  • 僅適用於正值

貸款金額資料的 log 轉換

原始與對數轉換資料的圖形比較

R 的特徵工程

正規化(Normalization)

正規化或縮放數值特徵以:

  • 避免單一特徵主導其他特徵
  • 便於解讀,因為量級可比且
  • 讓資料更適合建模

例如,貸款期數的數值差異很大

顯示貸款期數數值的長條圖。

R 的特徵工程

正規化(Normalization)

正規化或縮放數值特徵可:

  • 避免單一特徵主導其他特徵
  • 協助處理離群值與
  • 遺漏值
  • 讓資料更適合建模

正規化後的數值保留分布,但仍含變異。

長條圖顯示貸款金額數值,並疊加正規化資料。

R 的特徵工程

定義模型與 recipe

現在我們可以宣告一個羅吉斯迴歸模型,並加入一個 recipe 來填補、正規化與對數轉換相關特徵。

lr_model <- logistic_reg()

lr_recipe <- 
  recipe(Loan_Status ~., 
         data = train) %>%
  step_impute_knn(
    all_numeric_predictors())%>%
  step_normalize(Loan_Amount_Term) %>%
  step_log(all_numeric_predictors(),
           -Loan_Amount_Term, offset = 1)

列印 recipe 物件會顯示已套用步驟的摘要。

lr_recipe
Recipe

Inputs:

      role #variables
   outcome          1
 predictor          5

Operations:

K-nearest neighbor imputation for all_numeric_predictors()
Centering and scaling for Loan_Amount_Term
Log transformation on all_numeric_predictors(),-Loan_Amount_Term
R 的特徵工程

有效評估效能

我們定義一組衡量指標 roc_aucaccuracysens,用來評估工作流程物件 lr_fit

class_evaluate <- metric_set(
  roc_auc, accuracy, sens)

然後像呼叫一般函式一樣執行即可。

lr_aug %>% 
  class_evaluate(
    truth = Loan_Status, 
    estimate = .pred_class, 
    .pred_Y)

自訂指標集合

# A tibble: 3 × 3
  .metric  .estimator .estimate
  <chr>    <chr>          <dbl>
1 accuracy binary         0.813
2 sens     binary         0.467
3 roc_auc  binary         0.288
R 的特徵工程

一起來練習吧!

R 的特徵工程

Preparing Video For Download...