前回構築した決定木モデルの評価を行います。
予測値算出
まずは予測値を算出します。
[Google Colaboratory]
1 2 3 4 5 6 7 8 9 10 11 12
| y_train_pred = tree_reg.predict(X_train) y_test_pred = tree_reg.predict(X_test)
import numpy as np
y_train_pred = np.expand_dims(y_train_pred, 1) y_test_pred = np.expand_dims(y_test_pred, 1)
print(len(y_train_pred)) print(y_train_pred[:5]) print(len(y_test_pred)) print(y_test_pred[:5])
|
[実行結果]
可視化
散布図で予測値を可視化します。
[Google Colaboratory]
1 2 3 4 5 6 7
| plt.scatter(y_train_pred, y_train, label="train") plt.scatter(y_test_pred, y_test, label="test") plt.xlabel("Pred") plt.ylabel("True") plt.title("Scatter Plot") plt.legend() plt.show()
|
[実行結果]
線形回帰とは異なる分布になっています。
グラフからは、何種類かの特定の値が予測値として出力されているようです。
予測値として出力される値のパターンはリーフノードの数に依存します。
前回出力した樹形図のリーフノード数は8個だったので、予測値のパターンも8種類ということになります。
残差プロット
次に実測値と予測値の誤差をプロットしてみます。
[Google Colaboratory]
1 2 3 4 5 6 7 8 9 10 11
| def residual_plot(y_train_pred, y_train, y_test_pred, y_test): plt.scatter(y_train_pred, y_train_pred - y_train, label="train") plt.scatter(y_test_pred, y_test_pred - y_test, label="test") plt.plot([0, 50], [0,0] ,color="red") plt.xlabel("Pred") plt.ylabel("Pred - True") plt.title("Residual Plot") plt.legend() plt.show()
residual_plot(y_train_pred, y_train, y_test_pred, y_test)
|
[実行結果]
右側に外れ値がいくつかありますが、誤差の範囲が±10程度と、まずまずの結果となっていると思います。
精度評価スコア
精度評価スコアを算出します。
[Google Colaboratory]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score import numpy as np
def get_eval_score(y_true,y_pred): mae = mean_absolute_error(y_true,y_pred) mse = mean_squared_error(y_true,y_pred) rmse = np.sqrt(mse) r2score = r2_score(y_true,y_pred)
print(f" MAE = {mae}") print(f" MSE = {mse}") print(f" RMSE = {rmse}") print(f" R2 = {r2score}")
print("訓練データスコア") get_eval_score(y_train,y_train_pred) print("テストデータスコア") get_eval_score(y_test,y_test_pred)
|
[実行結果]
R2スコアが0.66であり、十分な精度となっていません。
次回は、ハイパーパラメータの設定で決定木の深さを変更し、スコアの向上を図ります。