Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
probml
GitHub Repository: probml/pyprobml
Path: blob/master/deprecated/scripts/betaHPD.py
1192 views
1
# -*- coding: utf-8 -*-
2
# based on https://github.com/probml/pmtk3/blob/master/demos/betaHPD.m
3
4
import superimport
5
6
import seaborn as sns
7
import numpy as np
8
from scipy.stats import beta
9
from scipy.optimize import fmin
10
import matplotlib.pyplot as plt
11
sns.set_style("ticks")
12
13
14
def HDIofICDF(dist_name, credMass=0.95, **args):
15
'''
16
Warning: This only works for unimodal distributions
17
Source : This was adapted from R to python from John K. Kruschke book, Doing bayesian data analysis,
18
by aloctavodia as part of the answer to the following stackoverflow question[1].
19
20
Reference:
21
1. https://stackoverflow.com/questions/22284502/highest-posterior-density-region-and-central-credible-region
22
'''
23
24
# freeze distribution with given arguments
25
distri = dist_name(**args)
26
# initial guess for HDIlowTailPr
27
incredMass = 1.0 - credMass
28
29
def intervalWidth(lowTailPr):
30
return distri.ppf(credMass + lowTailPr) - distri.ppf(lowTailPr)
31
32
# find lowTailPr that minimizes intervalWidth
33
HDIlowTailPr = fmin(intervalWidth, incredMass, ftol=1e-8, disp=False)[0]
34
# return interval as array([low, high])
35
return list(distri.ppf([HDIlowTailPr, credMass + HDIlowTailPr]))
36
37
38
a, b = 3, 9
39
alpha = 0.05
40
41
l = beta.ppf(alpha/2, a, b)
42
u = beta.ppf(1-alpha/2, a, b)
43
CI = [l,u]
44
45
HPD =HDIofICDF(beta, credMass=0.95, a=a, b=b)
46
47
xs = np.linspace(0.001, 0.999, 40)
48
ps = beta.pdf(xs, a, b)
49
50
names = ['CI','HPD']
51
linestyles = ['-', '-']
52
ints = [CI, HPD]
53
54
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
55
56
for i, inter in enumerate(ints):
57
58
# The corresponding pdf for each point of the interval.
59
l, u = inter
60
y1 = beta.pdf(l, a, b)
61
y2 = beta.pdf(u, a, b)
62
63
# The range of the plot
64
ax[i].set_xlim(0,1)
65
ax[i].set_ylim(0,3.5)
66
67
# The title of each plot
68
ax[i].set_title(names[i])
69
70
# The plot of the pdf of the distribution
71
ax[i].plot(xs, ps,
72
'-', lw=2, label='beta pdf', color="black")
73
74
# Plotting the intervals
75
ax[i].plot((l, l), (0, y1), color="blue")
76
ax[i].plot((l, u), (y1, y2), color="blue")
77
ax[i].plot((u, u), (y2, 0), color="blue")
78
79
plt.show()
80
81