Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/thinkbayes2
Path: blob/master/scripts/soccer_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: interarrival time in minutes
23
"""
24
x = data
25
lam = hypo / 90
26
like = thinkbayes2.EvalExponentialPdf(x, lam)
27
return like
28
29
def PredRemaining(self, rem_time, score):
30
"""Plots the predictive distribution for final number of goals.
31
32
rem_time: remaining time in the game in minutes
33
score: number of goals already scored
34
"""
35
metapmf = thinkbayes2.Pmf()
36
for lam, prob in self.Items():
37
lt = lam * rem_time / 90
38
pred = thinkbayes2.MakePoissonPmf(lt, 15)
39
metapmf[pred] = prob
40
#thinkplot.Pdf(pred, color='gray', alpha=0.1, linewidth=0.5)
41
42
mix = thinkbayes2.MakeMixture(metapmf)
43
mix += score
44
thinkplot.Hist(mix)
45
thinkplot.Show()
46
47
48
def main():
49
hypos = numpy.linspace(0, 12, 201)
50
suite = Soccer(hypos)
51
52
# the mean number of goals per game was 2.67
53
mean_rate = 2.67 / 2
54
mean_interarrival = 90 / mean_rate
55
56
# start with a prior based on the mean interarrival time
57
suite.Update(mean_interarrival)
58
thinkplot.Pdf(suite, label='prior')
59
print('prior mean', suite.Mean())
60
61
suite.Update(11)
62
thinkplot.Pdf(suite, label='posterior 1')
63
print('after one goal', suite.Mean())
64
65
suite.Update(12)
66
thinkplot.Pdf(suite, label='posterior 2')
67
print('after two goals', suite.Mean())
68
69
thinkplot.Show()
70
71
# plot the predictive distribution
72
suite.PredRemaining(90-23, 2)
73
74
75
if __name__ == '__main__':
76
main()
77
78