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
12
13
"""This file contains a partial solution to a problem from
14
MacKay, "Information Theory, Inference, and Learning Algorithms."
15
16
Exercise 3.15 (page 50): A statistical statement appeared in
17
"The Guardian" on Friday January 4, 2002:
18
19
When spun on edge 250 times, a Belgian one-euro coin came
20
up heads 140 times and tails 110. 'It looks very suspicious
21
to me,' said Barry Blight, a statistics lecturer at the London
22
School of Economics. 'If the coin weere unbiased, the chance of
23
getting a result as extreme as that would be less than 7%.'
24
25
MacKay asks, "But do these data give evidence that the coin is biased
26
rather than fair?"
27
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, 101):
70
if x != 50:
71
bias.Set(x, 1)
72
bias.Normalize()
73
74
# notice that we've changed the representation of the data
75
data = 140, 110
76
77
like_bias = AverageLikelihood(bias, data)
78
print('like_bias', like_bias)
79
80
like_fair = AverageLikelihood(fair, data)
81
print('like_fair', like_fair)
82
83
ratio = like_bias / like_fair
84
print('Bayes factor', ratio)
85
86
87
if __name__ == '__main__':
88
main()
89
90