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 Cookie(Pmf):
12
"""A map from string bowl ID to probablity."""
13
14
def __init__(self, hypos):
15
"""Initialize self.
16
17
hypos: sequence of string bowl IDs
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 the PMF with new data.
26
27
data: string cookie type
28
"""
29
for hypo in self.Values():
30
like = self.Likelihood(data, hypo)
31
self.Mult(hypo, like)
32
self.Normalize()
33
34
mixes = {
35
'Bowl 1':dict(vanilla=0.75, chocolate=0.25),
36
'Bowl 2':dict(vanilla=0.5, chocolate=0.5),
37
}
38
39
def Likelihood(self, data, hypo):
40
"""The likelihood of the data under the hypothesis.
41
42
data: string cookie type
43
hypo: string bowl ID
44
"""
45
mix = self.mixes[hypo]
46
like = mix[data]
47
return like
48
49
50
def main():
51
hypos = ['Bowl 1', 'Bowl 2']
52
53
pmf = Cookie(hypos)
54
55
pmf.Update('vanilla')
56
57
for hypo, prob in pmf.Items():
58
print hypo, prob
59
60
61
if __name__ == '__main__':
62
main()
63
64