使用監督式學習編碼類別資料

R 的特徵工程

Jorge Zazueta

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

認識監督式編碼

相對地,監督式編碼會利用輸出值,從名目型預測變數推導出數值特徵。

R 的特徵工程

認識監督式編碼

監督式編碼會利用輸出值,從名目型預測變數推導出數值特徵。

embed 套件中可用的部分監督式編碼函式**

Function Definition
step_lencode_glm() 使用概似編碼,將名目型預測變數轉換為一組分數,這些分數來自廣義線性模型。
step_lencode_bayes() 套用貝氏概似編碼,將名目型預測變數轉換為一組分數,這些分數來自以貝氏方法估計的廣義線性模型。
step_lencode_mixed() 將名目型預測變數轉換為一組分數,這些分數來自廣義線性混合模型。
R 的特徵工程

預測補助申請成功與否

我們想只用贊助者代碼來預測補助申請是否成功。

lr_model <- logistic_reg() # declare model

lr_recipe_glm <- # Set recipe glm
  recipe(class ~ sponsor_code, 
         data = grants_train) %>%
  step_lencode_glm(sponsor_code, 
                   # Declare outcome variable
                   outcome = vars(class))

lr_workflow_glm <- # Create Workflow
  workflow() %>%
  add_model(lr_model) %>%
  add_recipe(lr_recipe_glm)

工作流程摘要

lr_workflow_glm
-- Workflow ------------------------------------
Preprocessor: Recipe
Model: logistic_reg()

-- Preprocessor --------------------------------
1 Recipe Step

- step_lencode_glm()

-- Model --------------------------------------
Logistic Regression Model Specification (classification)

Computational engine: glm
R 的特徵工程

配適、擴增與評估

我們來配適並評估模型

lr_fit_glm <- # Fit
  lr_workflow_glm %>%
  fit(grants_train)

lr_aug_glm <- # Augment
  lr_fit_glm %>%
  augment(grants_test)

glm_model <- lr_aug_glm %>% # Assess
  class_evaluate(truth = class,
                 estimate = .pred_class,
                 .pred_successful)

效能結果存於 glm_model

glm_model
# A tibble: 2 × 3
  .metric  .estimator .estimate
  <chr>    <chr>          <dbl>
1 accuracy binary         0.728
2 roc_auc  binary         0.684
R 的特徵工程

彙整模型結果

我們建立 bayes_modelmixed_model,用來比較對應步驟的表現。

# Define model names
model <- c("glm", "glm",
           "bayes","bayes",
           "mixed", "mixed")
# Bind models in a tibble
models <- 
bind_rows(glm_model,
          bayes_model,
          mixed_model)%>%
  add_column(model = model)%>%
  select(-.estimator) %>%
  spread(model,.estimate)

實用的效能表

models
# A tibble: 2 × 4
  .metric  bayes   glm mixed
  <chr>    <dbl> <dbl> <dbl>
1 accuracy 0.718 0.728 0.720
2 roc_auc  0.686 0.684 0.682
R 的特徵工程

結果視覺化

使用 Gally 套件以平行座標圖視覺化結果。

# Libraries
library(GGally)

# Parallel coordinates chart
ggparcoord(models,
           columns = 2:4, 
           groupColumn = 1,
           scale="globalminmax",
           showPoints = TRUE)

所有模型的 accuracy 與 roc_auc 平行座標圖比較。

所有模型的 accuracy 與 roc_auc 平行座標圖比較。

R 的特徵工程

一起來練習吧!

R 的特徵工程

Preparing Video For Download...