相対誤差
この演習では、相対誤差と絶対誤差を比較します。モデリングの目的のため、相対誤差を次のように定義します。
$$ rel = \frac{(y - pred)}{y} $$
つまり、真の結果に対する相対的な誤差です。モデル全体の相対誤差は、相対二乗平均平方根誤差(root mean squared relative error)で測定します。
$$ rmse_{rel} = \sqrt(\overline{rel^2}) $$
ここで、\(\overline{rel^2}\) は \(rel^2\) の平均です。
サンプル用のデータセット fdata はあらかじめ読み込まれています。次の列が含まれます。
y: あるモデルが予測すべき真の出力。たとえば、来店時に顧客が使う金額だと想像してください。pred:yを予測するモデルの予測値。label: カテゴリ変数。yがsmall(小口購入)とlarge(大口購入)のどちらの集団に属するか。
small の購入を予測するモデルと、large の購入を予測するモデルのどちらが「より良い」かを知りたいとします。
この演習はコースの一部です
R による Supervised Learning:回帰
演習の手順
- 空欄を埋めてデータを確認します。大口購入は小口購入よりおよそ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")