Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/thinkbayes2
Path: blob/master/scripts/euro.py
1901 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
"""This file contains a partial solution to a problem from
11
MacKay, "Information Theory, Inference, and Learning Algorithms."
12
13
Exercise 3.15 (page 50): A statistical statement appeared in
14
"The Guardian" on Friday January 4, 2002:
15
16
When spun on edge 250 times, a Belgian one-euro coin came
17
up heads 140 times and tails 110. 'It looks very suspicious
18
to me,' said Barry Blight, a statistics lecturer at the London
19
School of Economics. 'If the coin were unbiased, the chance of
20
getting a result as extreme as that would be less than 7%.'
21
22
MacKay asks, "But do these data give evidence that the coin is biased
23
rather than fair?"
24
25
"""
26
27
import thinkbayes2
28
import thinkplot
29
30
31
class Euro(thinkbayes2.Suite):
32
"""Represents hypotheses about the probability of heads."""
33
34
def Likelihood(self, data, hypo):
35
"""Computes the likelihood of the data under the hypothesis.
36
37
hypo: integer value of x, the probability of heads (0-100)
38
data: string 'H' or 'T'
39
"""
40
x = hypo / 100.0
41
if data == 'H':
42
return x
43
else:
44
return 1-x
45
46
47
class Euro2(thinkbayes2.Suite):
48
"""Represents hypotheses about the probability of heads."""
49
50
def Likelihood(self, data, hypo):
51
"""Computes the likelihood of the data under the hypothesis.
52
53
hypo: integer value of x, the probability of heads (0-100)
54
data: tuple of (number of heads, number of tails)
55
"""
56
x = hypo / 100.0
57
heads, tails = data
58
like = x**heads * (1-x)**tails
59
return like
60
61
62
def UniformPrior():
63
"""Makes a Suite with a uniform prior."""
64
suite = Euro(range(0, 101))
65
return suite
66
67
68
def TrianglePrior():
69
"""Makes a Suite with a triangular prior."""
70
suite = Euro()
71
for x in range(0, 51):
72
suite.Set(x, x)
73
for x in range(51, 101):
74
suite.Set(x, 100-x)
75
suite.Normalize()
76
return suite
77
78
79
def RunUpdate(suite, heads=140, tails=110):
80
"""Updates the Suite with the given number of heads and tails.
81
82
suite: Suite object
83
heads: int
84
tails: int
85
"""
86
dataset = 'H' * heads + 'T' * tails
87
88
for data in dataset:
89
suite.Update(data)
90
91
92
def Summarize(suite):
93
"""Prints summary statistics for the suite."""
94
print(suite.Prob(50))
95
96
print('MLE', suite.MaximumLikelihood())
97
98
print('Mean', suite.Mean())
99
print('Median', suite.Percentile(50))
100
101
print('5th %ile', suite.Percentile(5))
102
print('95th %ile', suite.Percentile(95))
103
104
print('CI', suite.CredibleInterval(90))
105
106
107
def PlotSuites(suites, root):
108
"""Plots two suites.
109
110
suite1, suite2: Suite objects
111
root: string filename to write
112
"""
113
thinkplot.Clf()
114
thinkplot.PrePlot(len(suites))
115
thinkplot.Pmfs(suites)
116
117
thinkplot.Save(root=root,
118
xlabel='x',
119
ylabel='Probability',
120
formats=['pdf', 'eps'])
121
122
123
def main():
124
# make the priors
125
suite1 = UniformPrior()
126
suite1.name = 'uniform'
127
128
suite2 = TrianglePrior()
129
suite2.name = 'triangle'
130
131
# plot the priors
132
PlotSuites([suite1, suite2], 'euro2')
133
134
# update
135
RunUpdate(suite1)
136
Summarize(suite1)
137
138
RunUpdate(suite2)
139
Summarize(suite2)
140
141
# plot the posteriors
142
PlotSuites([suite1], 'euro1')
143
PlotSuites([suite1, suite2], 'euro3')
144
145
146
if __name__ == '__main__':
147
main()
148
149