Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

Repository for a workshop on Bayesian statistics

1430 views
1
"""This file contains code used in "Think Stats",
2
by Allen B. Downey, available from greenteapress.com
3
4
Copyright 2013 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
"""This file contains a partial solution to a problem from
15
MacKay, "Information Theory, Inference, and Learning Algorithms."
16
17
Exercise 3.15 (page 50): A statistical statement appeared in
18
"The Guardian" on Friday January 4, 2002:
19
20
When spun on edge 250 times, a Belgian one-euro coin came
21
up heads 140 times and tails 110. 'It looks very suspicious
22
to me,' said Barry Blight, a statistics lecturer at the London
23
School of Economics. 'If the coin weere unbiased, the chance of
24
getting a result as extreme as that would be less than 7%.'
25
26
MacKay asks, "But do these data give evidence that the coin is biased
27
rather than fair?"
28
29
"""
30
31
class Euro(thinkbayes.Suite):
32
33
def Likelihood(self, data, hypo):
34
"""Computes the likelihood of the data under the hypothesis.
35
36
data: tuple (#heads, #tails)
37
hypo: integer value of x, the probability of heads (0-100)
38
"""
39
x = hypo / 100.0
40
heads, tails = data
41
like = x**heads * (1-x)**tails
42
return like
43
44
45
def AverageLikelihood(suite, data):
46
"""Computes the average likelihood over all hypothesis in suite.
47
48
Args:
49
suite: Suite of hypotheses
50
data: some representation of the observed data
51
52
Returns:
53
float
54
"""
55
total = 0
56
57
for hypo, prob in suite.Items():
58
like = suite.Likelihood(data, hypo)
59
total += prob * like
60
61
return total
62
63
64
def main():
65
fair = Euro()
66
fair.Set(50, 1)
67
68
bias = Euro()
69
for x in range(0, 51):
70
bias.Set(x, x)
71
for x in range(51, 101):
72
bias.Set(x, 100-x)
73
bias.Normalize()
74
75
thinkplot.Pdf(bias)
76
thinkplot.Show()
77
78
# notice that we've changed the representation of the data
79
data = 140, 110
80
81
like_bias = AverageLikelihood(bias, data)
82
print('like_bias', like_bias)
83
84
like_fair = AverageLikelihood(fair, data)
85
print('like_fair', like_fair)
86
87
ratio = like_bias / like_fair
88
print('Bayes factor', ratio)
89
90
91
if __name__ == '__main__':
92
main()
93
94