Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

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