Zeel commited on
Commit
96092a4
·
1 Parent(s): 30a010d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -0
app.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import streamlit as st
3
+ import scipy.stats
4
+ import matplotlib.pyplot as plt
5
+ from matplotlib import rc
6
+
7
+ st.subheader("Bayesian Coin Toss")
8
+ st_col = st.columns(1)[0]
9
+
10
+ n_samples = st.slider('N_samples', 2, 40, 1)
11
+ n_heads = st.slider('N_heads', 2, 40, 1)
12
+ alpha = st.slider('Alpha', 0.5, 5.0, 0.5)
13
+ beta = st.slider('Beta', 0.5, 5.0, 0.5)
14
+
15
+ theta = np.linspace(0.01,0.99,100)
16
+ rc('font', size=20)
17
+ # rc('text', usetex=True)
18
+ fig, ax = plt.subplots(figsize=(12,6))
19
+ axs = ax.twinx()
20
+
21
+ def Bernoulli(theta, N, h):
22
+ return (theta ** h) * ((1-theta) ** (N-h))
23
+
24
+ def coin_toss(N, h, alpha, beta):
25
+ Likelihood = [Bernoulli(t,N,h) for t in theta]
26
+
27
+ ax.cla();axs.cla()
28
+ ax.plot(theta, Likelihood, label='Likelihood',color='b');
29
+ axs.plot(theta, scipy.stats.beta.pdf(theta, alpha,beta), label='Prior',color='k');
30
+ ax.set_xlabel('p(head)');
31
+ ax.vlines(h/N, *ax.get_ylim(), linestyle='--',label='MLE', color='b')
32
+ axs.text(h/N,2,'MLE', color='b')
33
+
34
+ axs.plot(theta, [scipy.stats.beta.pdf(t, h+alpha, N-h+beta) for t in theta], color='r')
35
+ ax.text(theta[0], Likelihood[0],'Likelihood', color='b')
36
+ axs.text(theta[-5], scipy.stats.beta.pdf(theta, alpha,beta)[-5],'Prior')
37
+ axs.text(alpha/(alpha+beta)-0.1,1,'Prior mean')
38
+ axs.text(theta[0],scipy.stats.beta.pdf(theta[0], h+alpha, N-h+beta),'Posterior',color='r')
39
+ axs.text((h+alpha)/(N+alpha+beta)-0.1,3,'Post. Mean',color='r')
40
+ ax.vlines(alpha/(alpha+beta), *ax.get_ylim(), linestyle='--',label='Prior mean',color='k')
41
+ ax.vlines((h+alpha)/(N+alpha+beta), *ax.get_ylim(), linestyle='--',label='Post. Mean',color='r')
42
+ # ax.set_title(f"n_samples={int(N)}, n_heads={int(h)}");
43
+ ax.tick_params(axis='y', colors='b')
44
+ axs.tick_params(axis='y', colors='r')
45
+ ax.set_ylabel('Likelihood',color='b')
46
+ axs.set_ylabel('Prior/Posterior', color='r', rotation=270, labelpad=30)
47
+ return fig
48
+
49
+
50
+
51
+ with st_col:
52
+ st.pyplot(coin_toss(n_samples, n_heads, alpha, beta))
53
+
54
+ hide_streamlit_style = """
55
+ <style>
56
+ #MainMenu {visibility: hidden;}
57
+ footer {visibility: hidden;}
58
+ </style>
59
+ """
60
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)