基于失业率模型进行预测
在本练习中,您将使用失业率模型 unemployment_model 对 unemployment 数据进行预测,并在训练数据 unemployment 上比较预测的女性失业率与实际观测到的女性失业率。您还将使用模型对 newrates 中的新数据进行预测。newrates 只包含 1 条观测,其中男性失业率为 5%。
针对 lm 模型,predict()(文档)的接口形式为:
predict(model, newdata)
您将使用 ggplot2 包绘图,因此需要先把预测列添加到 unemployment 数据框中。接着绘制"实际结果 vs 预测值"的图,并与代表"完美预测"的直线进行比较(也就是当实际结果等于预测值时的情形)。
绘制散点图的 ggplot2 命令如下,用于展示 dframe$outcome 与 dframe$pred 的关系(pred 在 x 轴,outcome 在 y 轴),并添加一条表示 outcome == pred 的蓝色直线:
ggplot(dframe, aes(x = pred, y = outcome)) +
geom_point() +
geom_abline(color = "blue")
unemployment、unemployment_model 和 newrates 已为您预加载。
本练习是课程的一部分
R 中的监督学习:回归
练习说明
- 使用
predict()基于unemployment数据预测女性失业率。将结果赋给新列:prediction。 - 使用
library()加载ggplot2包。 - 使用
ggplot()将预测值与实际失业率进行对比。将预测值放在 x 轴。观察结果与"完美预测"直线有多接近。 - 使用数据框
newrates预测当男性失业率为 5% 时预期的女性失业率。将结果赋给变量pred并打印。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# unemployment is available
summary(unemployment)
# newrates is available
newrates
# Predict female unemployment in the unemployment dataset
unemployment$prediction <- ___
# Load the ggplot2 package
___
# Make a plot to compare predictions to actual (prediction on x axis).
ggplot(___, aes(x = ___, y = ___)) +
___ +
geom_abline(color = "blue")
# Predict female unemployment rate when male unemployment is 5%
pred <- ___
pred