中位數補值

使用 R 的 caret 進行 Machine Learning

Max Kuhn

Software Engineer at RStudio and creator of caret

處理遺漏值

  • 多數模型需要數值,無法處理遺漏值
  • 常見作法:刪除含遺漏值的列
    • 可能造成資料偏誤
    • 讓模型過度自信
  • 更好的策略:中位數補值!
    • 以中位數取代遺漏值
    • 若資料隨機遺漏(MAR)表現良好
使用 R 的 caret 進行 Machine Learning

範例:mtcars

# Generate some data with missing values
data(mtcars)
set.seed(42)
mtcars[sample(1:nrow(mtcars), 10), "hp"] <- NA
# Split target from predictors
Y <- mtcars$mpg
X <- mtcars[, 2:4]
# Try to fit a caret model
library(caret)
model <- train(X, Y)
Error in train.default(X, Y) : Stopping 
使用 R 的 caret 進行 Machine Learning

簡單解法

# Now fit with median imputation
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 進行 Machine Learning

一起來練習吧!

使用 R 的 caret 進行 Machine Learning

Preparing Video For Download...