forked from probml/pyprobml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbb_grid_approx.py
executable file
·38 lines (32 loc) · 1.01 KB
/
bb_grid_approx.py
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
# 1d grid approixmation to beta binomial model
# https://github.com/aloctavodia/BAP
import pymc3 as pm
import numpy as np
import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
import arviz as az
def posterior_grid(heads, tails, grid_points=100):
grid = np.linspace(0, 1, grid_points)
prior = np.repeat(1/grid_points, grid_points) # uniform prior
likelihood = stats.binom.pmf(heads, heads+tails, grid)
posterior = likelihood * prior
posterior /= posterior.sum()
return grid, posterior
data = np.repeat([0, 1], (10, 3))
h = data.sum()
t = len(data) - h
grid, posterior = posterior_grid(h, t, 20)
plt.stem(grid, posterior, use_line_collection=True)
plt.title('grid approximation')
plt.yticks([])
plt.xlabel('θ');
plt.savefig('../figures/bb_grid.pdf')
plt.figure()
x = np.linspace(0, 1, 100)
xs = x #grid
post_exact = stats.beta.pdf(xs, h+1, t+1)
post_exact = post_exact / np.sum(post_exact)
plt.plot(xs, post_exact)
plt.title('exact posterior')
plt.savefig('../figures/bb_exact.pdf')