建立交互作用模型(2)
本練習屬於課程
R 中的監督式學習:回歸
練習說明
- 使用
kWayCrossValidation()(文件)建立 3 折交叉驗證的分割計畫。- 第一個引數是要分割的列數。
- 第二個引數是交叉驗證的折數。
- 你可以把函式的第 3 與第 4 個引數設為
NULL。
- 查看並執行範例程式碼,取得沒有交互作用之模型的 3 折交叉驗證預測,並指派到欄位
pred_add。 - 取得含有交互作用之模型的 3 折交叉驗證預測。把預測指派到欄位
pred_interaction。- 範例程式碼示範了整個流程。
- 使用你已經建立的同一個
splitPlan。
- 填入空格以:
- 使用
pivot_longer把兩組預測合併成單一欄位pred。 - 新增殘差欄位(真實結果 - 預測結果)。
- 針對每種模型類型計算交叉驗證預測的 RMSE。
- 使用
- 比較這些 RMSE。根據結果,你應該使用哪個模型?
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# alcohol is available
summary(alcohol)
# Both the formulae are available
fmla_add
fmla_interaction
# Create the splitting plan for 3-fold cross validation
set.seed(34245) # set the seed for reproducibility
splitPlan <- ___(___(___), ___, ___, ___)
# Sample code: Get cross-val predictions for main-effects only model
alcohol$pred_add <- 0 # initialize the prediction vector
for(i in 1:3) {
split <- splitPlan[[i]]
model_add <- lm(fmla_add, data = alcohol[split$train, ])
alcohol$pred_add[split$app] <- predict(model_add, newdata = alcohol[split$app, ])
}
# Get the cross-val predictions for the model with interactions
alcohol$pred_interaction <- 0 # initialize the prediction vector
for(i ___ ___) {
split <- ___
model_interaction <- lm(___, data = alcohol[split$train, ])
alcohol$___[split$app] <- predict(___, newdata = alcohol[split$app, ])
}
# Get RMSE
alcohol %>%
pivot_longer(cols=c('pred_add', 'pred_interaction'), names_to='modeltype', values_to='pred') %>%
mutate(residuals = ____) %>%
group_by(modeltype) %>%
summarize(rmse = ___(___(___)))