ベイズ線形回帰#

import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
# データを作成
n = 1000

from scipy.stats import multivariate_normal
mean = np.array([3, 5])
Sigma = np.array([
    [1, 0.5],
    [0.5, 2],
])
X = multivariate_normal.rvs(mean=mean, cov=Sigma, size=n, random_state=0)

import statsmodels.api as sm
X = sm.add_constant(X)

# 真のパラメータ
beta = np.array([2, 3, 4])

データが均一分散の場合#

# 均一分散の場合
e = np.random.normal(loc=0, scale=1, size=n)
y = X @ beta + e
# 頻度主義
import statsmodels.api as sm
ols = sm.OLS(y, X).fit(cov_type="HC1")
ols.summary()
OLS Regression Results
Dep. Variable: y R-squared: 0.981
Model: OLS Adj. R-squared: 0.981
Method: Least Squares F-statistic: 2.388e+04
Date: Wed, 11 Mar 2026 Prob (F-statistic): 0.00
Time: 22:22:31 Log-Likelihood: -1416.3
No. Observations: 1000 AIC: 2839.
Df Residuals: 997 BIC: 2853.
Df Model: 2
Covariance Type: HC1
coef std err z P>|z| [0.025 0.975]
const 1.7775 0.139 12.808 0.000 1.506 2.050
x1 2.9608 0.034 86.669 0.000 2.894 3.028
x2 4.0604 0.025 159.802 0.000 4.011 4.110
Omnibus: 3.954 Durbin-Watson: 2.039
Prob(Omnibus): 0.138 Jarque-Bera (JB): 4.369
Skew: 0.060 Prob(JB): 0.113
Kurtosis: 3.301 Cond. No. 25.9


Notes:
[1] Standard Errors are heteroscedasticity robust (HC1)
import pymc as pm
import arviz as az

model = pm.Model()
with model:
    beta0 = pm.Normal("beta0", mu=0, sigma=1)
    beta1 = pm.Normal("beta1", mu=0, sigma=1)
    beta2 = pm.Normal("beta2", mu=0, sigma=1)
    sigma = pm.HalfNormal("sigma", sigma=1)  # 分散なので非負の分布を使う

    # 平均値 mu
    mu = beta0 + beta1 * X[:, 1] + beta2 * X[:, 2]
    # 観測値をもつ確率変数は_obsとする
    y_obs = pm.Normal("y_obs", mu=mu, sigma=sigma, observed=y)

# モデルをGraphvizで表示
pm.model_to_graphviz(model)
../../_images/f969a9944c9f15b05e762aecdf9702507193c6115bd5824bcea53e8cb544c9b8.svg
# ベイズ線形回帰モデルをサンプリング
with model:
    idata = pm.sample(
        chains=2,
        tune=1000, # バーンイン期間の、捨てるサンプル数
        draws=2000, # 採用するサンプル数
        random_seed=0,
    )

# 各chainsの結果を表示
az.plot_trace(idata, figsize=[4, 4])
plt.tight_layout()
plt.show()
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [beta0, beta1, beta2, sigma]

Sampling 2 chains for 1_000 tune and 2_000 draw iterations (2_000 + 4_000 draws total) took 4 seconds.
We recommend running at least 4 chains for robust computation of convergence diagnostics
../../_images/d24d4ff4acf8d949c512e21ed27afa6a741389527c3cd7589070df80a73d63f9.png
az.plot_posterior(idata)
plt.show()
../../_images/3fffdeebf3ba4f5e6142bb28010e582fdaae81b8b7d1673a73ec95cfd3b3c1d1.png

データが不均一分散の場合#

# 不均一分散の場合
def normalize(x):
    return (x - x.min()) / (x.max() - x.min())

sigma = 1 + normalize(X[:, 1] + X[:, 2]) * 3
e = np.random.normal(loc=0, scale=sigma, size=n)
y = X @ beta + e

頻度主義 & 不均一分散に頑健な誤差推定#

# 頻度主義
import statsmodels.api as sm
ols = sm.OLS(y, X).fit(cov_type="HC1")
ols.summary()
OLS Regression Results
Dep. Variable: y R-squared: 0.885
Model: OLS Adj. R-squared: 0.885
Method: Least Squares F-statistic: 3267.
Date: Wed, 11 Mar 2026 Prob (F-statistic): 0.00
Time: 22:22:48 Log-Likelihood: -2344.7
No. Observations: 1000 AIC: 4695.
Df Residuals: 997 BIC: 4710.
Df Model: 2
Covariance Type: HC1
coef std err z P>|z| [0.025 0.975]
const 2.3467 0.334 7.034 0.000 1.693 3.001
x1 2.9034 0.089 32.591 0.000 2.729 3.078
x2 3.9906 0.065 61.392 0.000 3.863 4.118
Omnibus: 2.245 Durbin-Watson: 2.006
Prob(Omnibus): 0.325 Jarque-Bera (JB): 2.130
Skew: -0.079 Prob(JB): 0.345
Kurtosis: 3.162 Cond. No. 25.9


Notes:
[1] Standard Errors are heteroscedasticity robust (HC1)

↑ 切片の推定にバイアスが入っている

均一分散を想定したベイズ線形回帰#

import pymc as pm
import arviz as az

model = pm.Model()
with model:
    beta0 = pm.Normal("beta0", mu=0, sigma=1)
    beta1 = pm.Normal("beta1", mu=0, sigma=1)
    beta2 = pm.Normal("beta2", mu=0, sigma=1)
    sigma = pm.HalfNormal("sigma", sigma=1)  # 分散なので非負の分布を使う

    # 平均値 mu
    mu = beta0 + beta1 * X[:, 1] + beta2 * X[:, 2]
    # 観測値をもつ確率変数は_obsとする
    y_obs = pm.Normal("y_obs", mu=mu, sigma=sigma, observed=y)

# モデルをGraphvizで表示
pm.model_to_graphviz(model)
../../_images/f969a9944c9f15b05e762aecdf9702507193c6115bd5824bcea53e8cb544c9b8.svg
# ベイズ線形回帰モデルをサンプリング
with model:
    idata = pm.sample(
        chains=2,
        tune=1000, # バーンイン期間の、捨てるサンプル数
        draws=2000, # 採用するサンプル数
        random_seed=0,
    )

# 各chainsの結果を表示
az.plot_trace(idata, figsize=[4, 4])
plt.tight_layout()
plt.show()
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [beta0, beta1, beta2, sigma]

Sampling 2 chains for 1_000 tune and 2_000 draw iterations (2_000 + 4_000 draws total) took 4 seconds.
We recommend running at least 4 chains for robust computation of convergence diagnostics
../../_images/cfd36199fbccd6163ab9254d8fafe9bce2793f439055569697cb57fe7e6fb133.png
az.plot_posterior(idata)
plt.show()
../../_images/1b68ff0c9581f5a20f77b0ee8c7352efef89f8f836a2f3f185218204cf2347ab.png

不均一分散を想定したベイズ線形回帰(WIP)#

分散をxの関数にしたかった。以下コードで推定できるが個々の\(\sigma_i\)が別々に推定される形になって結果が見づらい。もっといい表し方はないものか。

import pymc as pm
import arviz as az

model = pm.Model()
with model:
    beta0 = pm.Normal("beta0", mu=0, sigma=1)
    beta1 = pm.Normal("beta1", mu=0, sigma=1)
    beta2 = pm.Normal("beta2", mu=0, sigma=1)

    # 誤差分散にも線形モデルを入れる
    w0 = pm.Normal("w0", mu=0, sigma=1)
    w1 = pm.Normal("w1", mu=0, sigma=1)
    w2 = pm.Normal("w2", mu=0, sigma=1)
    lam = pm.math.exp(w0 + w1 * X[:, 1] + w2 * X[:, 2])
    sigma = pm.Exponential("sigma", lam=lam)  # 分散なので非負の分布を使う

    # 平均値 mu
    mu = beta0 + beta1 * X[:, 1] + beta2 * X[:, 2]
    # 観測値をもつ確率変数は_obsとする
    y_obs = pm.Normal("y_obs", mu=mu, sigma=sigma, observed=y)

# モデルをGraphvizで表示
pm.model_to_graphviz(model)

# ベイズ線形回帰モデルをサンプリング
with model:
    idata = pm.sample(
        chains=2,
        tune=1000, # バーンイン期間の、捨てるサンプル数
        draws=2000, # 採用するサンプル数
        random_seed=0,
    )

# 各chainsの結果を表示
az.plot_trace(idata, figsize=[4, 4])
plt.tight_layout()
plt.show()

az.plot_posterior(idata)
plt.show()

参考#