This notebook presents example code and exercise solutions for Think Bayes.
Copyright 2016 Allen B. Downey
MIT License: https://opensource.org/licenses/MIT
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import classes from thinkbayes2
from thinkbayes2 import Pmf, Beta, MakeBinomialPmf
import thinkplot
import numpy as np
beta = Beta(5, 5)
prior = beta.MakePmf()
thinkplot.Pdf(prior)
thinkplot.decorate(xlabel='Prob Red Sox win (x)',
ylabel='PDF')
%psource beta.Update
beta.Update((15, 0))
posterior = beta.MakePmf()
thinkplot.Pdf(prior, color='gray', label='prior')
thinkplot.Pdf(posterior, label='posterior')
thinkplot.decorate(xlabel='Prob Red Sox win (x)',
ylabel='PDF')
posterior.mean()
0.8000000040157967
posterior.MAP()
0.83
posterior.CredibleInterval()
(0.66, 0.91)
x = posterior.Random()
0.94
np.sum(np.random.random(7) < x)
7
def simulate(k, dist):
x = dist.Random()
return np.sum(np.random.random(k) <= x)
simulate(7, posterior)
6
sample = [simulate(7, posterior) for i in range(100000)];
thinkplot.Hist(Pmf(sample))
np.mean(np.array(sample) >= 4)
0.94716