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
from thinkbayes import Pmf
9
10
11
class Monty(Pmf):
12
"""Map from string location of car to probability"""
13
14
def __init__(self, hypos):
15
"""Initialize the distribution.
16
17
hypos: sequence of hypotheses
18
"""
19
Pmf.__init__(self)
20
for hypo in hypos:
21
self.Set(hypo, 1)
22
self.Normalize()
23
24
def Update(self, data):
25
"""Updates each hypothesis based on the data.
26
27
data: any representation of the data
28
"""
29
for hypo in self.Values():
30
like = self.Likelihood(data, hypo)
31
self.Mult(hypo, like)
32
self.Normalize()
33
34
def Likelihood(self, data, hypo):
35
"""Compute the likelihood of the data under the hypothesis.
36
37
hypo: string name of the door where the prize is
38
data: string name of the door Monty opened
39
"""
40
if hypo == data:
41
return 0
42
elif hypo == 'A':
43
return 0.5
44
else:
45
return 1
46
47
48
def main():
49
hypos = 'ABC'
50
pmf = Monty(hypos)
51
52
data = 'B'
53
pmf.Update(data)
54
55
for hypo, prob in sorted(pmf.Items()):
56
print hypo, prob
57
58
59
if __name__ == '__main__':
60
main()
61
62