KNN 補值

使用 R 的 caret 進行 Machine Learning

Zach Mayer

Data Scientist at DataRobot and co-author of caret

處理遺漏值

  • 以中位數補值很快,但……
  • 若遺漏不是隨機,可能導致錯誤結果
  • k-nearest neighbors(KNN)補值
  • 依「相似」且非遺漏的列來補值
使用 R 的 caret 進行 Machine Learning

範例:非隨機遺漏

  • 假設小型車不回報 horsepower
  • 中位數補值在此不正確:它假設小車有中大型 horsepower
# Generate data with missing values
mtcars[mtcars$disp < 140, "hp"] <- NA
Y <- mtcars$mpg
X <- mtcars[, 2:4]

# Use median imputation
model <- train(X, Y, method = "glm", preProcess = "medianImpute")
print(min(model$results$RMSE))
3.612713
使用 R 的 caret 進行 Machine Learning

範例:非隨機遺漏

  • KNN 補值較佳
  • 使用與 disp/cyl 相近的車來補值
  • 可得更準確(但較慢)的模型
# Use KNN imputation
set.seed(42)
model <- train(
  X, Y, method = "glm", preProcess = "knnImpute"
)
print(min(model$results$RMSE))
3.558881

與中位數補值的 3.61 相比更好

使用 R 的 caret 進行 Machine Learning

一起來練習吧!

使用 R 的 caret 進行 Machine Learning

Preparing Video For Download...