ベイズ線形回帰#

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.982
Model: OLS Adj. R-squared: 0.982
Method: Least Squares F-statistic: 2.965e+04
Date: Wed, 01 Apr 2026 Prob (F-statistic): 0.00
Time: 07:13:56 Log-Likelihood: -1366.2
No. Observations: 1000 AIC: 2738.
Df Residuals: 997 BIC: 2753.
Df Model: 2
Covariance Type: HC1
coef std err z P>|z| [0.025 0.975]
const 2.0939 0.125 16.791 0.000 1.849 2.338
x1 2.9765 0.033 89.868 0.000 2.912 3.041
x2 4.0000 0.023 175.644 0.000 3.955 4.045
Omnibus: 0.474 Durbin-Watson: 1.958
Prob(Omnibus): 0.789 Jarque-Bera (JB): 0.562
Skew: 0.018 Prob(JB): 0.755
Kurtosis: 2.890 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/f3610f364f6d822fc34bb93bf0db68d18e2997dd981d9693e8893291ed444554.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 5 seconds.
We recommend running at least 4 chains for robust computation of convergence diagnostics
../../_images/c39e60bd90cb54a774fdb8700c39e88ac53f98e9d2249001230ad3a31bc81152.png
az.plot_posterior(idata)
plt.show()
../../_images/af62517e58da9ee1f6cb3207c0a43431a4eb9e000a6a2baeeb48d2648c15f080.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.900
Model: OLS Adj. R-squared: 0.900
Method: Least Squares F-statistic: 4449.
Date: Wed, 01 Apr 2026 Prob (F-statistic): 0.00
Time: 07:14:12 Log-Likelihood: -2283.1
No. Observations: 1000 AIC: 4572.
Df Residuals: 997 BIC: 4587.
Df Model: 2
Covariance Type: HC1
coef std err z P>|z| [0.025 0.975]
const 1.7223 0.297 5.796 0.000 1.140 2.305
x1 3.0795 0.079 38.943 0.000 2.925 3.235
x2 4.0004 0.061 66.088 0.000 3.882 4.119
Omnibus: 3.659 Durbin-Watson: 1.944
Prob(Omnibus): 0.161 Jarque-Bera (JB): 3.707
Skew: 0.146 Prob(JB): 0.157
Kurtosis: 2.943 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/f3610f364f6d822fc34bb93bf0db68d18e2997dd981d9693e8893291ed444554.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/ab238a748223b116b818c039fa282e3fcf9e4ca32d2538969431d695ec1fc8f7.png
az.plot_posterior(idata)
plt.show()
../../_images/4b0d9e793f38212ef8963050285cf631f8f6329f2194ae1d15e6a1e90d0325dc.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()

参考#