Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/thinkbayes2
Path: blob/master/scripts/cookie2.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 2012 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
from thinkbayes2 import Pmf
11
12
13
class Cookie(Pmf):
14
"""A map from string bowl ID to probablity."""
15
16
def __init__(self, hypos):
17
"""Initialize self.
18
19
hypos: sequence of string bowl IDs
20
"""
21
Pmf.__init__(self)
22
for hypo in hypos:
23
self.Set(hypo, 1)
24
self.Normalize()
25
26
def Update(self, data):
27
"""Updates the PMF with new data.
28
29
data: string cookie type
30
"""
31
for hypo in self.Values():
32
like = self.Likelihood(data, hypo)
33
self.Mult(hypo, like)
34
self.Normalize()
35
36
mixes = {
37
'Bowl 1':dict(vanilla=0.75, chocolate=0.25),
38
'Bowl 2':dict(vanilla=0.5, chocolate=0.5),
39
}
40
41
def Likelihood(self, data, hypo):
42
"""The likelihood of the data under the hypothesis.
43
44
data: string cookie type
45
hypo: string bowl ID
46
"""
47
mix = self.mixes[hypo]
48
like = mix[data]
49
return like
50
51
52
def main():
53
hypos = ['Bowl 1', 'Bowl 2']
54
55
pmf = Cookie(hypos)
56
57
pmf.Update('vanilla')
58
59
for hypo, prob in pmf.Items():
60
print(hypo, prob)
61
62
63
if __name__ == '__main__':
64
main()
65
66