Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/thinkbayes2
Path: blob/master/scripts/soccer2_soln.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 2014 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 numpy
11
import thinkbayes2
12
import thinkplot
13
14
15
class Soccer(thinkbayes2.Suite):
16
"""Represents hypotheses about."""
17
18
def Likelihood(self, data, hypo):
19
"""Computes the likelihood of the data under the hypothesis.
20
21
hypo: goal rate in goals per game
22
data: number of goals scored in a game
23
"""
24
goals = data
25
lam = hypo
26
like = thinkbayes2.EvalPoissonPmf(goals, lam)
27
return like
28
29
def PredictiveDist(self, label='pred'):
30
"""Computes the distribution of goals scored in a game.
31
32
returns: new Pmf (mixture of Poissons)
33
"""
34
metapmf = thinkbayes2.Pmf()
35
for lam, prob in self.Items():
36
pred = thinkbayes2.MakePoissonPmf(lam, 15)
37
metapmf[pred] = prob
38
39
mix = thinkbayes2.MakeMixture(metapmf, label=label)
40
return mix
41
42
43
def main():
44
hypos = numpy.linspace(0, 12, 201)
45
46
# start with a prior based on a pseudo observation
47
# chosen to yield the right prior mean
48
suite1 = Soccer(hypos, label='Germany')
49
suite1.Update(0.34)
50
suite2 = suite1.Copy(label='Argentina')
51
52
# update with the results of World Cup 2014 final
53
suite1.Update(1)
54
suite2.Update(0)
55
56
print('posterior mean Germany', suite1.Mean())
57
print('posterior mean Argentina', suite2.Mean())
58
59
# plot the posteriors
60
thinkplot.PrePlot(2)
61
thinkplot.Pdfs([suite1, suite2])
62
thinkplot.Show()
63
64
# compute posterior prob Germany is better than Argentina
65
post_prob = suite1 > suite2
66
print('posterior prob Germany > Argentina', post_prob)
67
68
prior_odds = 1
69
post_odds = post_prob / (1 - post_prob)
70
k = post_odds / prior_odds
71
print('Bayes factor', k)
72
73
# compute predictive distributions for goals scored in a rematch
74
pred1 = suite1.PredictiveDist(label='Germany')
75
pred2 = suite2.PredictiveDist(label='Argentina')
76
77
# plot the predictive distributions
78
thinkplot.PrePlot(2)
79
thinkplot.Pdfs([pred1, pred2])
80
thinkplot.Show()
81
82
# compute predictive probability of winning rematch
83
print('posterior prob Germany wins rematch', pred1 > pred2)
84
print('posterior prob Argentina wins rematch', pred2 > pred1)
85
86
87
if __name__ == '__main__':
88
main()
89
90