ランダムフォレスト回帰の多次元出力をプロットする

Beginner

This tutorial is from open-source community. Access the source code

はじめに

この実験では、マルチ出力回帰を行うためのマルチ出力メタ推定器の使用方法を示します。ネイティブにマルチ出力回帰をサポートしているランダムフォレスト回帰器を使用するため、結果を比較することができます。この実験の目的は、scikit-learn のMultiOutputRegressorを使用してマルチ出力回帰を行い、その結果を標準的なランダムフォレスト回帰器と比較する方法を示すことです。

VM のヒント

VM の起動が完了したら、左上隅をクリックしてノートブックタブに切り替え、Jupyter Notebook を使って練習しましょう。

Jupyter Notebook の読み込みには数秒かかる場合があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。

学習中に問題がある場合は、Labby にお問い合わせください。セッション終了後にフィードバックを提供してください。すぐに問題を解決いたします。

ライブラリのインポート

まず、必要なライブラリをインポートする必要があります。numpymatplotlib、および scikit-learn のRandomForestRegressortrain_test_splitMultiOutputRegressorを使用します。

import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.multioutput import MultiOutputRegressor

ランダムなデータセットの作成

次に、回帰に使用するランダムなデータセットを作成します。numpyを使って、-100 から 100 までの 600 個の x 値のセットを作成し、x 値のサインとコサインに基づいて計算される対応する y 値にいくらかのランダムノイズを加えます。

rng = np.random.RandomState(1)
X = np.sort(200 * rng.rand(600, 1) - 100, axis=0)
y = np.array([np.pi * np.sin(X).ravel(), np.pi * np.cos(X).ravel()]).T
y += 0.5 - rng.rand(*y.shape)

データを学習用とテスト用に分割する

scikit-learn のtrain_test_split関数を使って、データを 400 の学習用セットと 200 のテスト用セットに分割します。

X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=400, test_size=200, random_state=4)

ランダムフォレスト回帰器を作成する

scikit-learn のRandomForestRegressorを使って、最大深さ 30 と推定器 100 個のランダムフォレスト回帰器を作成します。

max_depth = 30
regr_rf = RandomForestRegressor(n_estimators=100, max_depth=max_depth, random_state=2)
regr_rf.fit(X_train, y_train)

多次元出力回帰器を作成する

基本的な推定器としてランダムフォレスト回帰器を使用して、MultiOutputRegressorを作成します。ステップ 4 と同じパラメータを使用します。

regr_multirf = MultiOutputRegressor(RandomForestRegressor(n_estimators=100, max_depth=max_depth, random_state=0))
regr_multirf.fit(X_train, y_train)

新しいデータに対する予測

テストデータに対する予測を行うために、ランダムフォレスト回帰器と多次元出力回帰器の両方を使用します。

y_rf = regr_rf.predict(X_test)
y_multirf = regr_multirf.predict(X_test)

結果をプロットする

2 つの回帰器の性能を比較するために、結果をプロットします。matplotlibを使用して、実際のテストデータ、ランダムフォレスト回帰器による予測、および多次元出力回帰器による予測の散布図を作成します。

plt.figure()
s = 50
a = 0.4
plt.scatter(y_test[:, 0], y_test[:, 1], edgecolor="k", c="navy", s=s, marker="s", alpha=a, label="Data")
plt.scatter(y_rf[:, 0], y_rf[:, 1], edgecolor="k", c="c", s=s, marker="^", alpha=a, label="RF score=%.2f" % regr_rf.score(X_test, y_test))
plt.scatter(y_multirf[:, 0], y_multirf[:, 1], edgecolor="k", c="cornflowerblue", s=s, alpha=a, label="Multi RF score=%.2f" % regr_multirf.score(X_test, y_test))
plt.xlim([-6, 6])
plt.ylim([-6, 6])
plt.xlabel("target 1")
plt.ylabel("target 2")
plt.title("Comparing Random Forests and the Multi-Output Meta Estimator")
plt.legend()
plt.show()

まとめ

この実験では、scikit-learn のMultiOutputRegressorを使用して多次元出力回帰を行う方法を示しました。ランダムなデータセットを使って、多次元出力回帰器と標準的なランダムフォレスト回帰器の性能を比較しました。結果は、多次元出力回帰器がランダムフォレスト回帰器よりもわずかに良い性能を示したことを示しています。