Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
probml
GitHub Repository: probml/pyprobml
Path: blob/master/deprecated/scripts/beta_binom_arviz.py
1192 views
1
import superimport
2
3
from scipy.stats import beta
4
5
np.random.seed(42)
6
theta_real = 0.35
7
ntrials = 100
8
data = stats.bernoulli.rvs(p=theta_real, size=ntrials)
9
10
N = ntrials; N1 = sum(data); N0 = N-N1; # Sufficient statistics
11
aprior = 1; bprior = 1; # prior
12
apost = aprior + N1; bpost = bprior + N0 # posterior
13
14
# Interval function
15
alpha = 0.05
16
CI1 = beta.interval(1-alpha, apost, bpost)
17
print('{:0.2f}--{:0.2f}'.format(CI1[0], CI1[1])) # (0.06:0.52)
18
19
# Use the inverse CDF (percent point function)
20
l = beta.ppf(alpha/2, apost, bpost)
21
u = beta.ppf(1-alpha/2, apost, bpost)
22
CI2 = (l,u)
23
print('{:0.2f}--{:0.2f}'.format(CI2[0], CI2[1])) # (0.06:0.52)
24
25
# Use Monte Carlo sampling
26
samples = beta.rvs(apost, bpost, size=10000)
27
samples = np.sort(samples)
28
CI3 = np.percentile(samples, 100*np.array([alpha/2, 1-alpha/2]))
29
print('{:0.2f}--{:0.2f}'.format(CI3[0], CI3[1])) # (0.06:0.51)
30
print(np.mean(samples))
31