-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbayesian_regression.py
More file actions
183 lines (154 loc) · 6.7 KB
/
Copy pathbayesian_regression.py
File metadata and controls
183 lines (154 loc) · 6.7 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
"""Bayesian linear regression demo with Numerics DEMCzs.
This file takes approximately 5 minutes to run. Once it is complete you will have a popup window of graphs
and tables will be output to the terminal.
"""
import os
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pythonnet
pythonnet.load("coreclr")
import clr
def _resolve_numerics_dll():
"""Resolve Numerics.dll from NUMERICS_DLL env var, the NuGet cache, or a local packages/ folder."""
env = os.environ.get("NUMERICS_DLL")
if env:
return Path(env)
cache = Path.home() / ".nuget" / "packages" / "rmc.numerics"
if cache.exists():
hits = sorted(cache.glob("*/lib/net8.0/Numerics.dll"), reverse=True)
if hits:
return hits[0]
for root in (Path.cwd(), Path(__file__).parent.parent):
local = sorted((root / "packages").glob("RMC.Numerics.*/lib/net8.0/Numerics.dll"), reverse=True)
if local:
return local[0]
raise FileNotFoundError(
"Numerics DLL not found. Install via `dotnet add package RMC.Numerics` "
"(pulls latest; append `--version 2.0.1` to pin) or set the NUMERICS_DLL "
"environment variable."
)
def load_numerics():
dll_path = _resolve_numerics_dll()
clr.AddReference(str(dll_path))
def main(seed=123):
load_numerics()
from Numerics.Distributions import IUnivariateDistribution, Normal, Uniform
from Numerics.Sampling.MCMC import DEMCzs, LogLikelihood, MCMCResults
from System.Collections.Generic import List
# NOTE FOR DEMO USERS:
# When calling Numerics MCMC samplers from Python via pythonnet, the samplers'
# internal parallel chains (Parallel.For) contend for Python's Global Interpreter
# Lock (GIL). This makes parallel execution slower than sequential. This is why
# we set sampler.ParallelizeChains = False below. It defaults to True, which
# works well in C#, but it slows the sampler down when driven from Python.
x = np.linspace(0, 10, 80)
true_a, true_b, true_sigma = 2.0, 1.4, 1.2
y = true_a + true_b * x + np.asarray(Normal(0, true_sigma).GenerateRandomValues(len(x),seed))
priors = List[IUnivariateDistribution]()
# Flat priors - we assume we know very little
priors.Add(Uniform(-10, 10))
priors.Add(Uniform(0, 5))
priors.Add(Uniform(0.1, 5))
# Define likelihood
def log_likelihood(params):
a, b, sigma = params[0], params[1], params[2]
residuals = y - (a + b * x)
dist = Normal(0, sigma)
return sum(dist.LogPDF(float(r)) for r in residuals)
# Run sampler
sampler = DEMCzs(priors, LogLikelihood(log_likelihood))
sampler.ParallelizeChains = False
sampler.Sample()
results = MCMCResults(sampler)
# Extract results
a_stats = results.ParameterResults[0].SummaryStatistics
b_stats = results.ParameterResults[1].SummaryStatistics
s_stats = results.ParameterResults[2].SummaryStatistics
posterior_df = pd.DataFrame(
[
{
"Parameter": "a",
"True": true_a,
"PosteriorMean": a_stats.Mean,
"Lower90": a_stats.LowerCI,
"Upper90": a_stats.UpperCI,
},
{
"Parameter": "b",
"True": true_b,
"PosteriorMean": b_stats.Mean,
"Lower90": b_stats.LowerCI,
"Upper90": b_stats.UpperCI,
},
{
"Parameter": "sigma",
"True": true_sigma,
"PosteriorMean": s_stats.Mean,
"Lower90": s_stats.LowerCI,
"Upper90": s_stats.UpperCI,
},
]
)
print("Bayesian regression (Numerics DEMCzs) parameter summary:")
print(posterior_df.to_string(index=False, float_format=lambda v: f"{v:,.4f}"))
chain = results.MarkovChains[0]
a_samples = np.array([chain[i].Values[0] for i in range(len(chain))], dtype=float)
b_samples = np.array([chain[i].Values[1] for i in range(len(chain))], dtype=float)
sigma_samples = np.array([chain[i].Values[2] for i in range(len(chain))], dtype=float)
# Mean-function credible band: E[y|x,theta] = a + b*x
# mu_draws[i,j] = a_i + b_i*x_j
mu_draws = a_samples[:, None] + b_samples[:, None] * x[None, :] # Model mean draws for every posterior sample at every x
y_hat_mean = mu_draws.mean(axis=0) # Average across posterior draws for each x_j
y_hat_low, y_hat_up = np.quantile(mu_draws, [0.05, 0.95], axis=0) # 90% interval for each x_j
fit_df = pd.DataFrame(
{
"x": x,
"y_observed": y,
"y_hat_mean": y_hat_mean,
"y_hat_low": y_hat_low,
"y_hat_up": y_hat_up,
}
)
print("\nFirst 10 fitted rows:")
print(fit_df.head(10).to_string(index=False, float_format=lambda v: f"{v:,.4f}"))
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# Data + fit band
axes[0, 0].scatter(x, y, color="black", s=20, alpha=0.6, label="Observed")
axes[0, 0].plot(x, y_hat_mean, color="steelblue", linewidth=2.5, label="Posterior mean line")
axes[0, 0].fill_between(x, y_hat_low, y_hat_up, color="steelblue", alpha=0.2, label="Approx 90% band")
axes[0, 0].set_title("Bayesian Regression Fit")
axes[0, 0].set_xlabel("x")
axes[0, 0].set_ylabel("y")
axes[0, 0].grid(True, alpha=0.3)
axes[0, 0].legend()
# Residual plot
residuals = y - y_hat_mean
axes[0, 1].scatter(y_hat_mean, residuals, s=20, alpha=0.6, color="coral")
axes[0, 1].axhline(0, color="black", linestyle="--", linewidth=1.5)
axes[0, 1].set_title("Residuals vs Fitted")
axes[0, 1].set_xlabel("Fitted")
axes[0, 1].set_ylabel("Residual")
axes[0, 1].grid(True, alpha=0.3)
# Posterior histograms
axes[1, 0].hist(a_samples, bins=40, alpha=0.6, label="a", color="slateblue", density=True)
axes[1, 0].hist(b_samples, bins=40, alpha=0.6, label="b", color="seagreen", density=True)
axes[1,0].axvline(true_a, color = 'blue', label = 'true a')
axes[1,0].axvline(true_b, color = 'green', label = 'true b')
axes[1, 0].set_title("Posterior Distributions: a and b")
axes[1, 0].set_xlabel("Value")
axes[1, 0].set_ylabel("Density")
axes[1, 0].legend()
axes[1, 0].grid(True, alpha=0.3)
axes[1, 1].hist(sigma_samples, bins=40, alpha=0.75, color="darkorange", density=True)
axes[1, 1].axvline(true_sigma, color="red", linestyle="--", linewidth=2, label="True sigma")
axes[1, 1].set_title("Posterior Distribution: sigma")
axes[1, 1].set_xlabel("sigma")
axes[1, 1].set_ylabel("Density")
axes[1, 1].legend()
axes[1, 1].grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
if __name__ == "__main__":
main()