使用训练/测试拆分评估模型
现在,您将用测试数据 mpg_test 来检验模型 mpg_model。
已为您提供函数 rmse() 和 r_squared() 以便计算 RMSE 和 R-squared:
rmse(predcol, ycol)
r_squared(predcol, ycol)
其中:
- predcol:预测值
- ycol:真实结果
您还将绘制预测值与真实结果的对比图。
一般来说,模型在训练数据上的表现优于测试数据(不过有时测试集会"运气好")。 性能有小幅差异是可以接受的;如果训练集上的表现明显更好,就说明存在问题。
数据框 mpg_train 和 mpg_test、模型 mpg_model 以及函数 rmse() 和 r_squared() 已预先加载。
本练习是课程的一部分
R 中的监督学习:回归
练习说明
- 在
mpg_train数据上,根据hwy预测城市油耗(cty)。将预测结果保存到列pred。 - 在
mpg_test数据上,根据hwy预测城市油耗(cty)。将预测结果保存到列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()