使用监督学习对分类数据进行编码

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

DNT_CURLY_TAG_3

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

可视化结果

使用GGally包的平行坐标图可视化结果。

# 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...