Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

Repository for a workshop on Bayesian statistics

1430 views
1
"""This file contains code for use with "Think Bayes",
2
by Allen B. Downey, available from greenteapress.com
3
4
Copyright 2012 Allen B. Downey
5
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
6
"""
7
8
from __future__ import print_function, division
9
10
import thinkbayes
11
import thinkplot
12
13
14
class Train(thinkbayes.Suite):
15
"""Represents hypotheses about how many trains the company has.
16
17
The likelihood function for the train problem is the same as
18
for the Dice problem.
19
"""
20
def Likelihood(self, data, hypo):
21
"""Computes the likelihood of the data under the hypothesis.
22
23
hypo: number of trains the carrier operates
24
data: the number of the observed train
25
"""
26
if hypo < data:
27
return 0
28
else:
29
return 1.0/hypo
30
31
32
33
def main():
34
hypos = range(1, 101)
35
suite = Train(hypos)
36
37
suite.Update(25)
38
print('Posterior mean', suite.Mean())
39
print('Posterior MLE', suite.MaximumLikelihood())
40
print('Posterior CI 90', suite.CredibleInterval(90))
41
42
thinkplot.PrePlot(1)
43
thinkplot.Pmf(suite, linewidth=5)
44
thinkplot.Save(root='train2',
45
xlabel='Number of trains',
46
ylabel='Probability',
47
formats=['png'])
48
49
thinkplot.Pmf(suite, linewidth=5, color='0.8')
50
suite.Update(42)
51
print('Posterior mean', suite.Mean())
52
print('Posterior MLE', suite.MaximumLikelihood())
53
print('Posterior CI 90', suite.CredibleInterval(90))
54
55
thinkplot.PrePlot(1)
56
thinkplot.Pmf(suite, linewidth=5)
57
thinkplot.Save(root='train3',
58
xlabel='Number of trains',
59
ylabel='Probability',
60
formats=['png'])
61
62
63
if __name__ == '__main__':
64
main()
65
66