Back to topic
Optional
Metropolis–Hastings on a 1D Gaussian
Run T MH steps with a Normal proposal; estimate acceptance rate and mean.
- Version
- v1
- Minutes
- ~25
- Evidence
- Self-check in the notebook
Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.
Download the notebook and run it locally. Its environment requirements are listed inside.
Notebook contents
Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.
Bayes · Metropolis–Hastings 1D / MH на 1D гауссе
Activity version: 1 · Seed: 0 · Данные: target , proposal , , .
Ожидаемые числа (seed 0)
| Quantity | Value | Tolerance |
|---|---|---|
| acceptance rate | ||
| sample mean | $ | \bar x |
Самопроверка в ноутбуке
Не влияет на mastery.
import numpy as np
rng = np.random.default_rng(0)
T = 2000
prop_sd = 0.5
x = 0.0
xs = np.empty(T)
accept = 0
for t in range(T):
prop = x + prop_sd * rng.normal()
log_alpha = -0.5 * (prop**2 - x**2) # N(0,1) target, symmetric proposal
if np.log(rng.uniform()) < min(0.0, log_alpha):
x = prop
accept += 1
xs[t] = x
acc_rate = accept / T
mean = xs.mean()
print("acc", acc_rate, "mean", mean)
assert 0.55 <= acc_rate <= 0.85
assert abs(mean) < 0.15
print("OK: MH 1D Gaussian")Самопроверка в ноутбуке
- acceptance rate в