ベイズ線形回帰#

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.412e+04
Date: Fri, 30 Jan 2026 Prob (F-statistic): 0.00
Time: 15:17:34 Log-Likelihood: -1412.4
No. Observations: 1000 AIC: 2831.
Df Residuals: 997 BIC: 2846.
Df Model: 2
Covariance Type: HC1
coef std err z P>|z| [0.025 0.975]
const 2.1136 0.134 15.736 0.000 1.850 2.377
x1 3.0355 0.034 89.121 0.000 2.969 3.102
x2 3.9657 0.025 161.144 0.000 3.918 4.014
Omnibus: 1.603 Durbin-Watson: 2.053
Prob(Omnibus): 0.449 Jarque-Bera (JB): 1.537
Skew: 0.016 Prob(JB): 0.464
Kurtosis: 2.811 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/15146f78f29a29be202e68b354b7be52f04196fe000a7dd4a97e7ba21c15cafa.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/252b85f3da6568ec664620a40e294bcebf647ac1a5cd84cb6f01b87aeb9f987b.png
az.plot_posterior(idata)
plt.show()
../../_images/b30afbdc2ee83e2591b8b02fbab5beb5a265bbde707d3c7be0c0ae40c6ae9579.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.884
Model: OLS Adj. R-squared: 0.884
Method: Least Squares F-statistic: 3203.
Date: Fri, 30 Jan 2026 Prob (F-statistic): 0.00
Time: 15:17:50 Log-Likelihood: -2358.5
No. Observations: 1000 AIC: 4723.
Df Residuals: 997 BIC: 4738.
Df Model: 2
Covariance Type: HC1
coef std err z P>|z| [0.025 0.975]
const 2.1080 0.339 6.225 0.000 1.444 2.772
x1 2.8304 0.086 32.948 0.000 2.662 2.999
x2 4.0723 0.063 64.778 0.000 3.949 4.195
Omnibus: 3.875 Durbin-Watson: 1.980
Prob(Omnibus): 0.144 Jarque-Bera (JB): 4.468
Skew: -0.024 Prob(JB): 0.107
Kurtosis: 3.324 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/15146f78f29a29be202e68b354b7be52f04196fe000a7dd4a97e7ba21c15cafa.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/0be08a216c4bb4a07ad57580633ae21ad0270c1a20fd0bec0d34160a2b7c931c.png
az.plot_posterior(idata)
plt.show()
../../_images/5537df9f1b57c4d490543935b7f1fb6d2b76918e360e1283b6d8de4ee7b65549.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()

参考#