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

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

言語 JA

加重最小二乗法 (WLS)

02.1.11

加重最小二乗法 (WLS)

最終更新 2020-06-17 読了時間 4 分
まとめ
加重最小二乗法(WLS)は、観測ごとに重み \(w_i\) を付けて残差の 2 乗に掛け、ばらつきの小さい信頼できる点ほど直線の決定に強く効かせる線形回帰です。理想的な重みは分散の逆数 \(1/\sigma_i^2\) で、ノイズが 5 倍大きい区間の点は重みが 1/25 になります。scikit-learn では LinearRegression().fit(X, y, sample_weight=weights) と書くだけで WLS になり、新しいクラスは要りません。このページでは \(x < 5\) でノイズ 0.5、\(x \ge 5\) でノイズ 2.5 と区間でばらつきが変わる 200 点に OLS と WLS を当て、傾き 1.2・切片 3.0 の真の直線にどちらが近いかを比べます。

直感 #

2 台の温度計で同じ現象を測り、片方は ±0.5 ℃、もう片方は ±2.5 ℃ の精度だとします。通常の最小二乗法は 2 台の読みを同じ重さで扱うので、精度の悪い温度計のばらつきがそのまま直線に乗ります。WLS は「精度の良い点の意見を 25 倍尊重する」ように重みを \(1/\sigma^2\) で付け直します。残差を 2 乗する前に重みを掛けるだけなので、解き方は最小二乗法と同じ閉じた式のままです。直線の位置はばらつきの小さい区間の点で決まり、ばらつきの大きい区間の点は「参考程度」に効きます。

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

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

見るポイント:誤差の大きい点の重みを下げるだけで、直線は多数派に戻る。WLS はこの重みを「残差の大きさ」ではなく「事前に分かっているノイズの分散」から \(1/\sigma_i^2\) として決めます。

式で書くとどこに重みが入るか #

最小二乗法の目的関数の各項に \(w_i\) を掛けただけで、\(w_i = 1\) なら通常の最小二乗法に戻ります。観測ごとに重み \(w_i > 0\) を与えて目的関数

$$ L(\boldsymbol\beta, b) = \sum_{i=1}^{n} w_i \left(y_i - (\boldsymbol\beta^\top \mathbf{x}_i + b)\right)^2 $$

を最小化します。理想的には \(w_i \propto 1/\sigma_i^2\)(分散の逆数)と設定し、信頼度の高いデータ点ほど重みを大きくします。下のコードではノイズの標準偏差が 0.5 と 2.5 なので、重みは 4.0 と 0.16 の 2 種類です。

Pythonを用いた実験や説明 #

次のコードは、真の直線 \(y = 1.2x + 3\) に、\(x < 5\) では標準偏差 0.5、\(x \ge 5\) では 2.5 のノイズを足した 200 点を作ります。同じ LinearRegression を sample_weight なし(OLS)と sample_weight=1/\sigma^2(WLS)で学習し、真の直線と 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
from __future__ import annotations

import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression

def run_weighted_vs_ols(
    n_samples: int = 200,
    threshold: float = 5.0,
    low_noise: float = 0.5,
    high_noise: float = 2.5,
    xlabel: str = "input $",
    ylabel: str = "output $",
    label_scatter: str = "observations (color=noise)",
    label_truth: str = "true line",
    label_ols: str = "OLS",
    label_wls: str = "WLS",
    title: str | None = None,
) -> dict[str, float]:
    """Compare OLS and weighted least squares on heteroscedastic data.

    Args:
        n_samples: Number of evenly spaced samples to generate.
        threshold: Breakpoint separating low- and high-noise regions.
        low_noise: Noise scale for the lower region.
        high_noise: Noise scale for the higher region.
        xlabel: Label for the x-axis.
        ylabel: Label for the y-axis.
        label_scatter: Legend label for the colored scatter plot.
        label_truth: Legend label for the ground-truth line.
        label_ols: Legend label for the OLS fit.
        label_wls: Legend label for the WLS fit.
        title: Optional title for the plot.

    Returns:
        Dictionary with slopes and intercepts of both fits.
    """
    rng = np.random.default_rng(7)

    X_vals: np.ndarray = np.linspace(0.0, 10.0, n_samples, dtype=float)
    true_y: np.ndarray = 1.2 * X_vals + 3.0

    noise_scale = np.where(X_vals < threshold, low_noise, high_noise)
    y_noisy = true_y + rng.normal(scale=noise_scale)

    weights = 1.0 / (noise_scale**2)
    X = X_vals[:, np.newaxis]

    ols = LinearRegression()
    ols.fit(X, y_noisy)

    wls = LinearRegression()
    wls.fit(X, y_noisy, sample_weight=weights)

    grid = np.linspace(0.0, 10.0, 200, dtype=float)[:, np.newaxis]
    ols_pred = ols.predict(grid)
    wls_pred = wls.predict(grid)

    fig, ax = plt.subplots(figsize=(10, 5))
    scatter = ax.scatter(
        X,
        y_noisy,
        c=noise_scale,
        cmap="coolwarm",
        s=25,
        label=label_scatter,
    )
    ax.plot(grid, 1.2 * grid.ravel() + 3.0, color="#2ca02c", label=label_truth)
    ax.plot(grid, ols_pred, color="#1f77b4", linestyle="--", linewidth=2, label=label_ols)
    ax.plot(grid, wls_pred, color="#d62728", linewidth=2, label=label_wls)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    if title:
        ax.set_title(title)
    ax.legend()
    fig.tight_layout()
    plt.show()

    return {
        "ols_slope": float(ols.coef_[0]),
        "ols_intercept": float(ols.intercept_),
        "wls_slope": float(wls.coef_[0]),
        "wls_intercept": float(wls.intercept_),
    }

metrics = run_weighted_vs_ols(
    xlabel="入力 $",
    ylabel="出力 $",
    label_scatter="観測値 (色=ノイズ)",
    label_truth="真の直線",
    label_ols="OLS",
    label_wls="WLS",
    title="重み付き最小二乗法とOLSの比較",
)
print(f"OLS の傾き: {metrics['ols_slope']:.3f}, 切片: {metrics['ols_intercept']:.3f}")
print(f"WLS の傾き: {metrics['wls_slope']:.3f}, 切片: {metrics['wls_intercept']:.3f}")

ノイズレベルが区間で異なるデータに WLS を適用する例ですの図

実行結果の読み方 #

散布図では \(x < 5\) の青い点が緑の直線に沿って細く並び、\(x \ge 5\) の赤い点は上下に大きく散っています。OLS(青の破線)は赤い点の偶然の偏りに影響されて真の直線から少しずれ、WLS(赤の実線)は重み 4.0 の青い点の帯に沿うので緑に近づきます。印字された傾きと切片では、どちらも真の 1.2 と 3.0 に近いものの、OLS の推定は不偏ですが分散が大きく、WLS の方が安定します。この差は乱数の種で変わるので、1 回の数値だけで優劣を決めず、図の「どの点の帯に沿っているか」で判断してください。

よくある質問 #

OLSとWLSはどう使い分ける? #

OLS(通常最小二乗法)は全観測が等分散であることを前提とします。残差プロットで分散が入力値に依存して変化する(不均一分散、ヘテロスケダスティシティ)ことが確認された場合にWLSを使います。Breusch-PaganテストやWhiteテストで不均一分散を統計的に検定してから判断するのが標準的です。

重みの決め方は? #

主な設定方法は 4 つあります。各観測の誤差分散が既知または推定できる場合は分散の逆数 \(w_i = 1/\hat{\sigma}_i^2\) を使います。複数回測定の平均値を使う場合は、平均の分散が \(\sigma^2 / n_i\) になるので測定回数 \(n_i\) を重みにします。分散が未知なら2 段階推定で、まず OLS の残差を計算し、残差の絶対値の逆数(または残差の 2 乗を \(x\) で回帰した推定分散の逆数)を重みにします。センサー精度や信頼度スコアなどドメイン知識から設計する方法もあります。

WLSとGLSの違いは? #

WLS(加重最小二乗法)は誤差の分散のみが観測ごとに異なる場合(対角共分散行列)を扱います。GLS(一般化最小二乗法)は誤差間に相関がある場合も含む一般的な枠組みで、WLSはGLSの特殊ケースです。時系列の自己相関がある場合はFeasible GLS(FGLS)が必要です。

sklearnでWLSを実行するには? #

LinearRegression.fit(X, y, sample_weight=weights)のsample_weight引数に重みベクトルを渡すだけです。重みは正の値で、分散の逆数(1 / sigma**2)として設定するのが理想的です。


参考文献 #

  • Carroll, R. J., & Ruppert, D. (1988). Transformation and Weighting in Regression. Chapman & Hall.
  • Seber, G. A. F., & Lee, A. J. (2012). Linear Regression Analysis (2nd ed.). Wiley.