开始使用免费开始使用

使用训练/测试拆分评估模型

现在,您将用测试数据 mpg_test 来检验模型 mpg_model。 已为您提供函数 rmse()r_squared() 以便计算 RMSE 和 R-squared:

rmse(predcol, ycol)
r_squared(predcol, ycol)

其中:

  • predcol:预测值
  • ycol:真实结果

您还将绘制预测值与真实结果的对比图。

一般来说,模型在训练数据上的表现优于测试数据(不过有时测试集会"运气好")。 性能有小幅差异是可以接受的;如果训练集上的表现明显更好,就说明存在问题。

数据框 mpg_trainmpg_test、模型 mpg_model 以及函数 rmse()r_squared() 已预先加载。

本练习是课程的一部分

R 中的监督学习:回归

查看课程

练习说明

  • mpg_train 数据上,根据 hwy 预测城市油耗(cty)。将预测结果保存到列 pred
  • mpg_test 数据上,根据 hwy 预测城市油耗(cty)。将预测结果保存到列 pred
  • 使用 rmse() 分别评估测试集与训练集的 RMSE。进行比较。两者表现是否相近?
  • 使用 r_squared() 做同样的比较。两者表现是否相近?
  • 使用 ggplot2test 数据上绘制预测值与 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()
编辑并运行代码