开始使用免费开始使用

相对误差

在本练习中,您将比较相对误差与绝对误差。就建模而言,我们将相对误差定义为:

$$ 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 中的监督学习:回归

查看课程

练习说明

  • 填空以检查数据。请注意,large 购买通常比 small 购买大约大 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")
编辑并运行代码