開始使用免費開始

10 折交叉驗證

就像你在影片中看到的,比起單一隨機的訓練/測試切分,使用多個有系統的測試集來驗證模型會更好。所幸,caret 套件提供了很簡單的做法:

model <- train(y ~ ., my_data)

caret 支援多種交叉驗證方式。你可以用 trainControl() 指定交叉驗證的型式與折數,並將其傳入 train()trControl 參數:

model <- train(
  y ~ ., 
  my_data,
  method = "lm",
  trControl = trainControl(
    method = "cv", 
    number = 10,
    verboseIter = TRUE
  )
)

請注意,建模的方法要傳給主要的 train() 函式,而交叉驗證的方法要傳給 trainControl() 函式。

本練習屬於課程

使用 R 的 caret 進行 Machine Learning

檢視課程

練習說明

  • 使用 train() 函式與 10 折交叉驗證,對 diamonds 資料集中除了 price 之外的所有變數進行線性迴歸,以預測 price
  • 將模型列印到主控台並檢視結果。(注意:我們已從完整的 diamonds 資料集中取了一個子集以加快執行,但名稱仍為 diamonds。)

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Fit lm model using 10-fold CV: model
model <- train(
  ___, 
  ___,
  method = "lm",
  trControl = trainControl(
    method = "cv", 
    number = ___,
    verboseIter = TRUE
  )
)

# Print model to console
編輯並執行程式碼