K_DM Book
用語集
対象者 標準
対象者別の入口 →

対象者の設定はこのブラウザの中にだけ保存されます。

言語 JA

多項式回帰

入門

02.1.4

多項式回帰

最終更新 2020-03-11 読了時間 4 分
まとめ
多項式回帰は、入力 \(x\) から \(x^2, x^3, \dots\) の列を作って線形回帰に渡すことで、曲がった関係を直線のモデルで当てはめる手法です。係数の決め方は最小二乗法のままなので、PolynomialFeatures で列を増やして LinearRegression に渡すだけで動きます。次数 degree を上げるほど曲線は自由に曲がりますが、訓練データに合わせすぎてデータ範囲の外で暴れるので、交差検証で次数を選ぶか リッジ回帰 を併用します。このページでは 3 次曲線にノイズを足した 200 点に直線と 3 次の多項式を当てはめ、MSE の差と範囲外での振る舞いを比べます。

先に 線形回帰 で LinearRegression が残差二乗和を最小にする仕組みを見ておくと、このページで変わるのは「渡す列の数」だけだと分かります。

直感 #

気温と光熱費のように U 字に並ぶデータに直線を引くと、両端でも中央でも点から外れます。多項式回帰は新しいアルゴリズムを使うのではなく、表に \(x^2\) の列、\(x^3\) の列を足してから同じ線形回帰を走らせます。重回帰なら各変数の冪に加えて \(x_1 x_2\) のような交差項も PolynomialFeatures が自動で作りますが、モデルは係数 \(\mathbf{w}\) について線形のままなので、解は反復なしに閉じた式で求まります。

何が起きているか(ステップで見る) #

コードを読む前に、この手法が図の上で何をしているかを追ってみましょう。「再生」を押すか、スライダーを動かすと 1 手順ずつ進みます。

見るポイント:次数を上げると訓練には合うが、未知データでは途中から悪化する。その分岐点がモデル選択。下のコードの degree=3 は、データを作った真の関数と同じ次数をあえて選んだものです。

式で書くと何が変わるか #

変わるのは入力 \(x\) の置き換えだけで、損失は同じ残差二乗和です。入力ベクトル \(\mathbf{x} = (x_1, \dots, x_m)\) に対して次数 \(d\) の多項式基底 \(\phi(\mathbf{x})\) を作り、線形回帰を行います。例えば \(m = 2, d = 2\) なら

$$ \phi(\mathbf{x}) = (1, x_1, x_2, x_1^2, x_1 x_2, x_2^2) $$

となり、モデルは

$$ y = \mathbf{w}^\top \phi(\mathbf{x}) $$

で表されます。\(\phi\) の各成分が図の「曲がり」を担う部品で、\(x_1^2\) の係数が放物線の開き具合、\(x_1 x_2\) の係数が 2 変数の相互作用を表します。次数 \(d\) を増やすと特徴量の数は \(m = 10, d = 3\) で 286 列まで膨らむため、実務では 2〜3 次から試し、必要に応じてリッジ回帰を併用します。

Pythonを用いた実験や説明 #

次のコードは、真の関係 \(y = 0.5x^3 - 1.2x^2 + 2x + 1.5\) に標準偏差 2.0 のノイズを足した 200 点を作り、LinearRegression だけの直線と、PolynomialFeatures(degree=3) を前に置いた 3 次の曲線を同じ図に重ねます。訓練データの MSE を 2 つ並べて、曲線にした効果を数値でも確認します。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
from __future__ import annotations

import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures

def compare_polynomial_regression(
    n_samples: int = 200,
    degree: int = 3,
    noise_scale: float = 2.0,
    label_observations: str = "observations",
    label_true_curve: str = "true curve",
    label_linear: str = "linear regression",
    label_poly_template: str = "degree-{degree} polynomial",
) -> tuple[float, float]:
    """Fit linear vs. polynomial regression to a cubic trend and plot the results.

    Args:
        n_samples: Number of synthetic samples generated along the curve.
        degree: Polynomial degree used in the feature expansion.
        noise_scale: Standard deviation of the Gaussian noise added to targets.
        label_observations: Legend label for scatter observations.
        label_true_curve: Legend label for the underlying true curve.
        label_linear: Legend label for the linear regression fit.
        label_poly_template: Format string for the polynomial label.

    Returns:
        A tuple containing the mean-squared errors of (linear, polynomial) models.
    """
    rng = np.random.default_rng(seed=42)

    x: np.ndarray = np.linspace(-3.0, 3.0, n_samples, dtype=float)
    y_true: np.ndarray = 0.5 * x**3 - 1.2 * x**2 + 2.0 * x + 1.5
    y_noisy: np.ndarray = y_true + rng.normal(scale=noise_scale, size=x.shape)

    X: np.ndarray = x[:, np.newaxis]

    linear_model = LinearRegression()
    linear_model.fit(X, y_noisy)
    poly_model = make_pipeline(
        PolynomialFeatures(degree=degree, include_bias=False),
        LinearRegression(),
    )
    poly_model.fit(X, y_noisy)

    grid: np.ndarray = np.linspace(-3.5, 3.5, 300, dtype=float)[:, np.newaxis]
    linear_pred: np.ndarray = linear_model.predict(grid)
    poly_pred: np.ndarray = poly_model.predict(grid)
    true_curve: np.ndarray = (
        0.5 * grid.ravel()**3 - 1.2 * grid.ravel()**2 + 2.0 * grid.ravel() + 1.5
    )

    linear_mse: float = float(mean_squared_error(y_noisy, linear_model.predict(X)))
    poly_mse: float = float(mean_squared_error(y_noisy, poly_model.predict(X)))

    fig, ax = plt.subplots(figsize=(10, 5))
    ax.scatter(
        X,
        y_noisy,
        s=20,
        color="#ff7f0e",
        alpha=0.6,
        label=label_observations,
    )
    ax.plot(
        grid,
        true_curve,
        color="#2ca02c",
        linewidth=2,
        label=label_true_curve,
    )
    ax.plot(
        grid,
        linear_pred,
        color="#1f77b4",
        linestyle="--",
        linewidth=2,
        label=label_linear,
    )
    ax.plot(
        grid,
        poly_pred,
        color="#d62728",
        linewidth=2,
        label=label_poly_template.format(degree=degree),
    )
    ax.set_xlabel("input $x$")
    ax.set_ylabel("output $y$")
    ax.legend()
    fig.tight_layout()
    plt.show()

    return linear_mse, poly_mse

degree = 3
linear_mse, poly_mse = compare_polynomial_regression(
    degree=degree,
    label_observations="観測データ",
    label_true_curve="真の曲線",
    label_linear="線形回帰",
    label_poly_template="次数{degree}の多項式",
)
print(f"線形回帰のMSE: {linear_mse:.3f}")
print(f"次数{degree}の多項式回帰のMSE: {poly_mse:.3f}")

以下は 3 次の多項式特徴量を追加した線形回帰モデルで、曲線的なデータを学習する例ですの図

結果の読み方 #

青の破線(直線)は S 字の中央付近で点から大きく外れ、linear_mse はノイズ分散 4.0 よりかなり大きくなります。赤の 3 次曲線は緑の真の曲線にほぼ重なり、poly_mse はノイズ分散 4.0 に近い値まで下がります。この差が「列を 3 本に増やしただけ」で得られる効果です。ただし両端 \(x = \pm 3.5\) では赤が緑から離れ始めていて、データ範囲の外で多項式が信用できないことも同じ図から読めます。

使いどころと落とし穴 #

散布図を見て 1〜2 回曲がる滑らかな関係なら、degree=2 か 3 の多項式回帰が最初の候補です。落とし穴は 3 つあります。1 つ目は次数の選び方で、訓練 MSE だけを見ると次数は上げるほど良く見えるため、cross_val_score で選びます。2 つ目はスケールで、\(x\) が 1000 のオーダーだと \(x^3\) は \(10^9\) になり係数の推定が不安定になるので、StandardScaler を PolynomialFeatures の前に置きます。3 つ目は外挿で、データ範囲の外では多項式は必ず \(\pm\infty\) に向かうため、範囲外の予測が必要なら SVR など別の手法を検討します。

次数と回帰曲線 #

多項式の次数を変えると、フィッティングの柔軟さと過学習リスクがどう変わるか確認できます。

参考文献 #

  • Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer.
  • Hastie, T., Tibshirani, R., & Friedman, J. (2009). The Elements of Statistical Learning. Springer.