中位数填补

在 R 中使用 caret 的机器学习

Max Kuhn

Software Engineer at RStudio and creator of caret

处理缺失值

  • 大多数模型只接受数值,无法处理缺失值
  • 常见做法:删除含缺失的数据行
    • 可能引入偏差
    • 使模型过度自信
  • 更好的策略:中位数填补
    • 用中位数替换缺失值
    • 若数据是随机缺失(MAR)效果好
在 R 中使用 caret 的机器学习

示例:mtcars

# 生成含缺失值的数据
data(mtcars)
set.seed(42)
mtcars[sample(1:nrow(mtcars), 10), "hp"] <- NA
# 将目标与自变量分开
Y <- mtcars$mpg
X <- mtcars[, 2:4]
# 尝试拟合 caret 模型
library(caret)
model <- train(X, Y)
Error in train.default(X, Y) : Stopping 
在 R 中使用 caret 的机器学习

简单的解决方案

# 使用中位数填补后再拟合
model <- train(X, Y, preProcess = "medianImpute")
print(model)
Random Forest 

32 samples
 3 predictor

Pre-processing: median imputation (3) 
Resampling: Bootstrapped (25 reps) 
Summary of sample sizes: 32, 32, 32, 32, 32, 32, ... 
Resampling results across tuning parameters:

  mtry  RMSE      Rsquared 
  2     2.617096  0.8234652
  3     2.670550  0.8164535

RMSE was used to select the optimal model using the smallest value.
The final value used for the model was mtry = 2. 
在 R 中使用 caret 的机器学习

开始练习!

在 R 中使用 caret 的机器学习

Preparing Video For Download...