Relative error
在這個練習中,你會比較相對誤差與絕對誤差。為了建模,我們將相對誤差定義為:
$$ rel = \frac{(y - pred)}{y} $$
也就是說,誤差是相對於真實結果而定義的。你會用均方根相對誤差來衡量模型的整體相對誤差:
$$ rmse_{rel} = \sqrt(\overline{rel^2}) $$
其中 \(\overline{rel^2}\) 是 \(rel^2\) 的平均值。
範例(玩具)資料集 fdata 已預先載入。它包含以下欄位:
y:某個模型要預測的真實輸出;你可以把它想成顧客每次到店消費的金額。pred:用來預測y的模型之預測值。label:類別型欄位:y來自消費金額較small或較large的族群。
你想知道哪個模型做得「比較好」:是針對 small 消費的模型,還是針對 large 的模型。
本練習屬於課程
R 中的監督式學習:回歸
練習說明
- 填空以檢視資料。注意大型消費大約比小型消費高出 100 倍。
- 填空以建立誤差欄位:
- 將殘差定義為
y - pred。 - 將相對誤差定義為
residual / y。
- 將殘差定義為
- 填空以計算並比較 RMSE 與相對 RMSE。
- 絕對誤差如何比較?相對誤差呢?
- 檢視「預測值對真實結果」的散佈圖。
- 依你的看法,哪個模型做得「比較好」?
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# fdata is available
summary(fdata)
# Examine the data: generate the summaries for the groups large and small:
fdata %>%
group_by(label) %>% # group by small/large purchases
summarize(min = ___, # min of y
mean = ___, # mean of y
max = ___) # max of y
# Fill in the blanks to add error columns
fdata2 <- fdata %>%
group_by(label) %>% # group by label
mutate(residual = ___, # Residual
relerr = ___) # Relative error
# Compare the rmse and rmse.rel of the large and small groups:
fdata2 %>%
group_by(label) %>%
summarize(rmse = ___, # RMSE
rmse.rel = ___) # Root mean squared relative error
# Plot the predictions for both groups of purchases
ggplot(fdata2, aes(x = pred, y = y, color = label)) +
geom_point() +
geom_abline() +
facet_wrap(~ label, ncol = 1, scales = "free") +
ggtitle("Outcome vs prediction")