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 Version1():
61
suite = Euro(xrange(0, 101))
62
heads, tails = 140, 110
63
dataset = 'H' * heads + 'T' * tails
64
65
for data in dataset:
66
suite.Update(data)
67
68
return suite
69
70
71
def Version2():
72
suite = Euro(xrange(0, 101))
73
heads, tails = 140, 110
74
dataset = 'H' * heads + 'T' * tails
75
76
suite.UpdateSet(dataset)
77
return suite
78
79
80
def Version3():
81
suite = Euro2(xrange(0, 101))
82
heads, tails = 140, 110
83
84
suite.Update((heads, tails))
85
return suite
86
87
88
def main():
89
90
suite = Version3()
91
print suite.Mean()
92
93
thinkplot.Pmf(suite)
94
thinkplot.Show()
95
96
97
98
if __name__ == '__main__':
99
main()
100
101