處理資訊量低的預測變數

使用 R 的 caret 進行 Machine Learning

Zach Mayer

Data Scientist at DataRobot and co-author of caret

無(或低)變異的變數

  • 有些變數幾乎不提供資訊
    • 常數(即無變異)
    • 近似常數(即變異很低)
  • 在交叉驗證的某一折中,欄位可能變成常數
    • 會造成模型問題
  • 通常會移除變異極低的變數
使用 R 的 caret 進行 Machine Learning

範例:mtcars 中的常數欄

# Reproduce dataset from last video
data(mtcars)
set.seed(42)
mtcars[sample(1:nrow(mtcars), 10), "hp"] <- NA
Y <- mtcars$mpg
X <- mtcars[, 2:4]
# Add constant-valued column to mtcars
X$bad <- 1
使用 R 的 caret 進行 Machine Learning

範例:mtcars 中的常數欄

# Try to fit a model with PCA + glm
model <- train(
  X, Y, method = "glm", 
  preProcess = c("center", "scale", "medianImpute", "pca"))
Warning in preProcess.default(thresh = 0.95, k = 5, method = c("medianImpute",  :
  These variables have zero variances: bad
Something is wrong; all the RMSE metric values are missing:
      RMSE        Rsquared  
 Min.   : NA   Min.   : NA  
 1st Qu.: NA   1st Qu.: NA  
 Median : NA   Median : NA  
 Mean   :NaN   Mean   :NaN  
 3rd Qu.: NA   3rd Qu.: NA  
 Max.   : NA   Max.   : NA  
 NA's   :1     NA's   :1   
使用 R 的 caret 進行 Machine Learning

caret 再次救援

  • 「zv」會移除常數欄位
  • 「nzv」會移除近似常數欄位
# Have caret remove those columns during modeling
set.seed(42)
model <- train(
  X, Y, method = "glm", 
  preProcess = c("zv", "center", "scale", "medianImpute", "pca")
)
min(model$results$RMSE)
3.402557
使用 R 的 caret 進行 Machine Learning

一起來練習吧!

使用 R 的 caret 進行 Machine Learning

Preparing Video For Download...