使用訓練/測試切分來評估模型
現在你要在測試資料 mpg_test 上測試模型 mpg_model。
已提供 rmse() 與 r_squared() 兩個函式,方便你計算 RMSE 與 R-squared:
rmse(predcol, ycol)
r_squared(predcol, ycol)
其中:
- predcol:預測值
- ycol:實際目標值
你也會繪製「預測值 vs. 實際值」的圖。
通常,模型在訓練資料上的表現會優於測試資料(不過有時候測試集可能「運氣不錯」)。 輕微的差異可以接受;如果訓練集的表現明顯更好,就代表有問題。
mpg_train 與 mpg_test 這兩個資料框、mpg_model 模型,以及 rmse() 與 r_squared() 函式都已預先載入。
本練習屬於課程
R 中的監督式學習:回歸
練習說明
- 在
mpg_train資料中,使用hwy來預測市區油耗,並將預測結果指派到欄位pred。 - 在
mpg_test資料中,使用hwy來預測市區油耗,並將預測結果指派到欄位pred。 - 使用
rmse()分別評估測試集與訓練集的 RMSE。比較兩者,表現是否相近? - 使用
r_squared()做相同的比較。表現是否相近? - 使用
ggplot2繪製在test資料上的預測值對cty的散佈圖。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Examine the objects that have been loaded
ls.str()
# predict cty from hwy for the training set
mpg_train$pred <- ___
# predict cty from hwy for the test set
mpg_test$pred <- ___
# Evaluate the rmse on both training and test data and print them
(rmse_train <- ___)
(rmse_test <- ___)
# Evaluate the r-squared on both training and test data.and print them
(rsq_train <- ___)
(rsq_test <- ___)
# Plot the predictions (on the x-axis) against the outcome (cty) on the test data
ggplot(___, aes(x = ___, y = ___)) +
geom_point() +
geom_abline()