試験データで大豆モデルを使って予測する
この演習では、前の演習の大豆モデル(model.lin と model.gam、すでに読み込み済み)を新しいデータ soybean_test に適用します。
この演習はコースの一部です
R による Supervised Learning:回帰
演習の手順
- 線形モデル
model.linによる予測値を列soybean_test$pred.linに作成します。 - GAM モデル
model.gamによる予測値を列soybean_test$pred.gamに作成します。- GAM モデルでは
predict()は行列を返すので、as.numeric()でベクトルに変換してください。
- GAM モデルでは
- 空欄を埋めて、予測列を
pivot_longer()でキー列modeltype、値列predの1列にまとめます。ロング形式のデータフレーム名はsoybean_longとします。 - 両モデルの RMSE を計算して比較します。
- どちらのモデルのほうが良いですか?
- 各モデルの予測と実際の平均葉重を比較するコードを実行します。
Timeに対するweightの散布図。Timeに対する予測値(pred)の点と線のプロット。- 線形モデルはときどき負の重さを予測することに注意してください! 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")