テスト/トレイン分割でモデルを評価する
テストデータ 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 による Supervised Learning:回帰
演習の手順
mpg_trainデータで、hwyから市街地燃費を予測し、予測値を列predに代入します。mpg_testデータでも同様に、hwyから市街地燃費を予測し、予測値を列predに代入します。rmse()を使って、テストセットと学習セットの RMSE を評価します。比較して、性能は近いでしょうか?r_squared()でも同じ評価を行います。性能は近いでしょうか?ggplot2を使って、テストデータでの予測値を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()