はじめに
このチュートリアルでは、Python の人気のある機械学習ライブラリである Scikit-Learn を使って、Kernel Ridge Regression (KRR) と Support Vector Regression (SVR) を比較します。両モデルは、カーネルトリックを用いて非線形関数を学習します。KRR と SVR は、損失関数とフィッティング方法において異なります。我々は、正弦波の目的関数と、5 番目のデータポイントに強いノイズが加えられた人工的なデータセットを使います。
VM のヒント
VM の起動が完了したら、左上隅をクリックして Notebook タブに切り替えて、Jupyter Notebook を使った練習にアクセスします。
時々、Jupyter Notebook が読み込み終わるまで数秒待つ必要があります。Jupyter Notebook の制限により、操作の検証は自動化できません。
学習中に問題に直面した場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。私たちは迅速に問題を解決いたします。
サンプルデータを生成する
我々は、正弦波の目的関数と、5 番目のデータポイントに強いノイズが加えられたデータセットを生成します。
import numpy as np
## サンプルデータを生成する
rng = np.random.RandomState(42)
X = 5 * rng.rand(10000, 1)
y = np.sin(X).ravel()
## ターゲットにノイズを加える
y[::5] += 3 * (0.5 - rng.rand(X.shape[0] // 5))
X_plot = np.linspace(0, 5, 100000)[:, None]
カーネルベースの回帰モデルを構築する
我々は、Scikit-Learn の GridSearchCV を使って KRR と SVR モデルを構築し、最適なハイパーパラメータを見つけます。
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVR
from sklearn.kernel_ridge import KernelRidge
train_size = 100
## SVR モデル
svr = GridSearchCV(
SVR(kernel="rbf", gamma=0.1),
param_grid={"C": [1e0, 1e1, 1e2, 1e3], "gamma": np.logspace(-2, 2, 5)},
)
## KRR モデル
kr = GridSearchCV(
KernelRidge(kernel="rbf", gamma=0.1),
param_grid={"alpha": [1e0, 0.1, 1e-2, 1e-3], "gamma": np.logspace(-2, 2, 5)},
)
SVR と Kernel Ridge Regression の時間を比較する
我々は、ステップ 2 で見つけた最適なハイパーパラメータを使って、SVR と KRR モデルのフィッティングと予測の時間を比較します。
import time
## SVR をフィッティングする
t0 = time.time()
svr.fit(X[:train_size], y[:train_size])
svr_fit = time.time() - t0
## SVR モデルの最適なパラメータとスコアを表示する
print(f"Best SVR with params: {svr.best_params_} and R2 score: {svr.best_score_:.3f}")
print("SVR complexity and bandwidth selected and model fitted in %.3f s" % svr_fit)
## KRR をフィッティングする
t0 = time.time()
kr.fit(X[:train_size], y[:train_size])
kr_fit = time.time() - t0
## KRR モデルの最適なパラメータとスコアを表示する
print(f"Best KRR with params: {kr.best_params_} and R2 score: {kr.best_score_:.3f}")
print("KRR complexity and bandwidth selected and model fitted in %.3f s" % kr_fit)
## SVR のサポートベクトル比を計算する
sv_ratio = svr.best_estimator_.support_.shape[0] / train_size
print("Support vector ratio: %.3f" % sv_ratio)
## SVR を使って予測する
t0 = time.time()
y_svr = svr.predict(X_plot)
svr_predict = time.time() - t0
print("SVR prediction for %d inputs in %.3f s" % (X_plot.shape[0], svr_predict))
## KRR を使って予測する
t0 = time.time()
y_kr = kr.predict(X_plot)
kr_predict = time.time() - t0
print("KRR prediction for %d inputs in %.3f s" % (X_plot.shape[0], kr_predict))
結果を見る
RBF カーネルの複雑さ/正則化と帯域幅の両方がグリッドサーチを使って最適化された場合、KRR と SVR の学習モデルを可視化します。
import matplotlib.pyplot as plt
sv_ind = svr.best_estimator_.support_
plt.scatter(
X[sv_ind],
y[sv_ind],
c="r",
s=50,
label="SVR support vectors",
zorder=2,
edgecolors=(0, 0, 0),
)
plt.scatter(X[:100], y[:100], c="k", label="data", zorder=1, edgecolors=(0, 0, 0))
plt.plot(
X_plot,
y_svr,
c="r",
label="SVR (fit: %.3fs, predict: %.3fs)" % (svr_fit, svr_predict),
)
plt.plot(
X_plot, y_kr, c="g", label="KRR (fit: %.3fs, predict: %.3fs)" % (kr_fit, kr_predict)
)
plt.xlabel("data")
plt.ylabel("target")
plt.title("SVR versus Kernel Ridge")
_ = plt.legend()
学習と予測時間を可視化する
我々は、異なるサイズの学習セットに対する KRR と SVR のフィッティングと予測の時間を可視化します。
_, ax = plt.subplots()
sizes = np.logspace(1, 3.8, 7).astype(int)
for name, estimator in {
"KRR": KernelRidge(kernel="rbf", alpha=0.01, gamma=10),
"SVR": SVR(kernel="rbf", C=1e2, gamma=10),
}.items():
train_time = []
test_time = []
for train_test_size in sizes:
t0 = time.time()
estimator.fit(X[:train_test_size], y[:train_test_size])
train_time.append(time.time() - t0)
t0 = time.time()
estimator.predict(X_plot[:1000])
test_time.append(time.time() - t0)
plt.plot(
sizes,
train_time,
"o-",
color="r" if name == "SVR" else "g",
label="%s (train)" % name,
)
plt.plot(
sizes,
test_time,
"o--",
color="r" if name == "SVR" else "g",
label="%s (test)" % name,
)
plt.xscale("log")
plt.yscale("log")
plt.xlabel("Train size")
plt.ylabel("Time (seconds)")
plt.title("Execution Time")
_ = plt.legend(loc="best")
学習曲線を可視化する
我々は、KRR と SVR の学習曲線を可視化します。
from sklearn.model_selection import LearningCurveDisplay
_, ax = plt.subplots()
svr = SVR(kernel="rbf", C=1e1, gamma=0.1)
kr = KernelRidge(kernel="rbf", alpha=0.1, gamma=0.1)
common_params = {
"X": X[:100],
"y": y[:100],
"train_sizes": np.linspace(0.1, 1, 10),
"scoring": "neg_mean_squared_error",
"negate_score": True,
"score_name": "Mean Squared Error",
"std_display_style": None,
"ax": ax,
}
LearningCurveDisplay.from_estimator(svr, **common_params)
LearningCurveDisplay.from_estimator(kr, **common_params)
ax.set_title("Learning curves")
ax.legend(handles=ax.get_legend_handles_labels()[0], labels=["SVR", "KRR"])
plt.show()
まとめ
このチュートリアルでは、Scikit-Learn を使って Kernel Ridge Regression (KRR) と Support Vector Regression (SVR) を比較しました。我々は、正弦波状の目的関数と 5 番目のデータポイントに強いノイズが加えられたデータセットを生成しました。我々は、Scikit-Learn の GridSearchCV を使って KRR と SVR モデルを構築し、最適なハイパーパラメータを見つけました。見つけた最適なハイパーパラメータを使って、SVR と KRR モデルのフィッティングと予測の時間を比較しました。RBF カーネルの複雑さ/正則化と帯域幅の両方がグリッドサーチを使って最適化された場合、KRR と SVR の学習モデルを可視化しました。また、異なるサイズの学習セットに対する KRR と SVR のフィッティングと予測の時間を可視化しました。最後に、KRR と SVR の学習曲線を可視化しました。