分类变量输入

R 中的监督学习:回归

Nina Zumel and John Mount

Win-Vector, LLC

示例:饮食对减重的影响

WtLoss24 ~ Diet + Age + BMI
Diet Age BMI WtLoss24
Med 59 30.67 -6.7
Low-Carb 48 29.59 8.4
Low-Fat 52 32.9 6.3
Med 53 28.92 8.3
Low-Fat 47 30.20 6.3
R 中的监督学习:回归

model.matrix()

model.matrix(WtLoss24 ~ Diet + Age + BMI, data = diet)
  • 全为数值
  • 将具有 N 个水平的分类变量转换为 N - 1 个指示变量
R 中的监督学习:回归

用指示变量表示类别

原始数据

Diet Age ...
Med 59 ...
Low-Carb 48 ...
Low-Fat 52 ...
Med 53 ...
Low-Fat 47 ...

模型矩阵

(Int) DietLow-Fat DietMed ...
1 0 1 ...
1 0 0 ...
1 1 0 ...
1 0 1 ...
1 1 0 ...
  • 参考水平:"Low-Carb"
R 中的监督学习:回归

解读指示变量

线性模型:

$$ WtLoss24 = \beta_{0} + \beta_{DietLow} x_{DietLow} + \beta_{DietMed} x_{DietMed} + \beta_{Age} x_{Age} + \beta_{BMI} x_{BMI} $$

lm(WtLoss24 ~ Diet + Age + BMI, data = diet))
Coefficients:
      (Intercept)        DietLow-Fat     DietMed  
         -1.37149           -2.32130    -0.97883  
              Age                BMI  
          0.12648            0.01262
R 中的监督学习:回归

独热编码的问题

  • 水平过多会有问题
    • 例:邮政编码(约 40,000 个)
  • 不要将哈希用于几何方法!
R 中的监督学习:回归

Passons à la pratique !

R 中的监督学习:回归

Preparing Video For Download...