在测试数据上用大豆模型进行预测
在本练习中,您将把上一个练习中的大豆模型(model.lin 和 model.gam,已加载)应用到新数据:soybean_test。
本练习是课程的一部分
R 中的监督学习:回归
练习说明
- 使用线性模型
model.lin生成预测,创建列soybean_test$pred.lin。 - 使用 GAM 模型
model.gam生成预测,创建列soybean_test$pred.gam。- 对于 GAM 模型,
predict()方法返回的是矩阵,请用as.numeric()将矩阵转换为向量。
- 对于 GAM 模型,
- 填空,将预测列使用
pivot_longer()转为长表,键列为modeltype,数值列为pred。将该长数据框命名为soybean_long。 - 计算并比较两个模型的 RMSE。
- 哪个模型表现更好?
- 运行代码,将每个模型的预测与真实的平均叶片重量进行比较。
- 绘制
weight随Time变化的散点图。 - 绘制预测值(
pred)随Time变化的点线图。 - 注意线性模型有时会预测出负的重量!GAM 模型会这样吗?
- 绘制
交互式实操练习
通过完成这段示例代码来试试这个练习。
# soybean_test is available
summary(soybean_test)
# Get predictions from linear model
soybean_test$pred.lin <- ___(___, newdata = ___)
# Get predictions from gam model
soybean_test$pred.gam <- ___(___(___, newdata = ___))
# Pivot the predictions into a "long" dataset
soybean_long <- soybean_test %>%
pivot_longer(cols = c(___, ___), names_to = ___, values_to = ___)
# Calculate the rmse
soybean_long %>%
mutate(residual = weight - pred) %>% # residuals
group_by(modeltype) %>% # group by modeltype
summarize(rmse = ___(___(___))) # calculate the RMSE
# Compare the predictions against actual weights on the test data
soybean_long %>%
ggplot(aes(x = Time)) + # the column for the x axis
geom_point(aes(y = weight)) + # the y-column for the scatterplot
geom_point(aes(y = pred, color = modeltype)) + # the y-column for the point-and-line plot
geom_line(aes(y = pred, color = modeltype, linetype = modeltype)) + # the y-column for the point-and-line plot
scale_color_brewer(palette = "Dark2")