開始使用免費開始

在測試資料上用 soybean 模型進行預測

在這個練習中,你要把前一個練習的 soybean 模型(model.linmodel.gam,已載入)套用到新資料:soybean_test

本練習屬於課程

R 中的監督式學習:回歸

檢視課程

練習說明

  • 建立 soybean_test$pred.lin 欄位,放入線性模型 model.lin 的預測。
  • 建立 soybean_test$pred.gam 欄位,放入 GAM 模型 model.gam 的預測。
    • 對於 GAM 模型,predict() 會回傳矩陣,請用 as.numeric() 將矩陣轉成向量。
  • 填空,使用 pivot_longer() 把上述預測欄位轉為單一數值欄 pred,並以 modeltype 作為鍵欄位。將長格式資料框命名為 soybean_long
  • 計算並比較兩個模型的 RMSE。
    • 哪個模型表現較好?
  • 執行程式碼,比較各模型的預測與實際的平均葉重。
    • 繪製 weightTime 的散佈圖。
    • 繪製預測值(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")
  
編輯並執行程式碼