@@ -58,11 +58,8 @@ def __setitem__(self, val, p):
58
58
59
59
def normalize (self ):
60
60
"""Make sure the probabilities of all values sum to 1.
61
-
62
61
Returns the normalized distribution.
63
-
64
62
Raises a ZeroDivisionError if the sum of the values is 0.
65
-
66
63
>>> P = ProbDist('Flip'); P['H'], P['T'] = 35, 65
67
64
>>> P = P.normalize()
68
65
>>> print '%5.3f %5.3f' % (P.prob['H'], P.prob['T'])
@@ -89,8 +86,7 @@ class JointProbDist(ProbDist):
89
86
0.25
90
87
>>> P[dict(X=0, Y=1)] = 0.5
91
88
>>> P[dict(X=0, Y=1)]
92
- 0.5
93
- """
89
+ 0.5"""
94
90
def __init__ (self , variables ):
95
91
update (self , prob = {}, variables = variables , vals = DefaultDict ([]))
96
92
@@ -124,7 +120,6 @@ class BoolCpt:
124
120
random variable conditioned on its parents."""
125
121
126
122
def __init__ (self , table_data ):
127
-
128
123
"""Initialize the table.
129
124
130
125
table_data may have one of three forms, depending on the
@@ -148,12 +143,10 @@ def __init__(self, table_data):
148
143
>>> cpt = BoolCpt({T: 0.2, F: 0.7})
149
144
>>> cpt = BoolCpt({(T, T): 0.2, (T, F): 0.3, (F, T): 0.5, (F, F): 0.7})
150
145
"""
151
-
152
146
# A little work here makes looking up values MUCH simpler
153
147
# later on. We transform table_data into the standard form
154
148
# of a dictionary {(value, ...): number, ...} even if
155
149
# the tuple has just 0 or 1 value.
156
-
157
150
if type (table_data ) == float : # no parents, 0-tuple
158
151
self .table_data = {(): table_data }
159
152
elif type (table_data ) == dict :
@@ -171,7 +164,6 @@ def __init__(self, table_data):
171
164
raise Exception ("wrong table_data type: %s" % table_data )
172
165
173
166
def p (self , value , parent_vars , event ):
174
-
175
167
"""Return the conditional probability P(value | parent_vars =
176
168
parent_values), where parent_values are the values of
177
169
parent_vars in event.
@@ -197,15 +189,12 @@ def p(self, value, parent_vars, event):
197
189
0.375
198
190
>>> BoolCpt(0.75).p(False, [], {})
199
191
0.25
200
-
201
192
"""
202
-
203
193
return self .p_values (value , event_values (event , parent_vars ))
204
194
205
195
def p_values (self , xvalue , parent_values ):
206
196
"""Return P(X = xvalue | parents = parent_values),
207
197
where parent_values is a tuple, even if of only 0 or 1 element.
208
-
209
198
>>> cpt = BoolCpt(0.25)
210
199
>>> cpt.p_values(F, ())
211
200
0.75
@@ -221,7 +210,6 @@ def p_values(self, xvalue, parent_values):
221
210
>>> cpt.p_values(F, (F, F))
222
211
0.38
223
212
"""
224
-
225
213
ptrue = self .table_data [parent_values ] # True or False
226
214
if xvalue :
227
215
return ptrue
@@ -244,12 +232,10 @@ def rand(self, parents, event):
244
232
>>> cpt.rand(['A', 'B'], {'A': True, 'B': False}) in [True, False]
245
233
True
246
234
"""
247
-
248
235
return (random () <= self .p (True , parents , event ))
249
236
250
237
def event_values (event , vars ):
251
238
"""Return a tuple of the values of variables vars in event.
252
-
253
239
>>> event_values ({'A': 10, 'B': 9, 'C': 8}, ['C', 'A'])
254
240
(8, 10)
255
241
>>> event_values ((1, 2), ['C', 'A'])
@@ -289,7 +275,6 @@ def enumerate_joint(vars, values, P):
289
275
#______________________________________________________________________________
290
276
291
277
class BayesNet :
292
-
293
278
"""Bayesian network containing only boolean variable nodes."""
294
279
295
280
def __init__ (self , nodes = []):
@@ -306,23 +291,17 @@ def observe(self, var, val):
306
291
307
292
def variable_node (self , var ):
308
293
"""Returns the node for the variable named var.
309
-
310
294
>>> burglary.variable_node('Burglary').variable
311
- 'Burglary'
312
- """
313
-
295
+ 'Burglary'"""
314
296
for n in self .nodes :
315
297
if n .variable == var :
316
298
return n
317
299
raise Exception ("No such variable: %s" % var )
318
300
319
301
def variables (self ):
320
302
"""Returns the list of names of the variables.
321
-
322
303
>>> burglary.variables()
323
- ['Burglary', 'Earthquake', 'Alarm', 'JohnCalls', 'MaryCalls']
324
- """
325
-
304
+ ['Burglary', 'Earthquake', 'Alarm', 'JohnCalls', 'MaryCalls']"""
326
305
return [n .variable for n in self .nodes ]
327
306
328
307
def variable_values (self , var ):
@@ -366,9 +345,7 @@ def enumeration_ask (X, e, bn):
366
345
>>> p = enumeration_ask('Burglary',
367
346
... {'JohnCalls': True, 'MaryCalls': True}, burglary)
368
347
>>> p.show_approx()
369
- 'False: 0.716, True: 0.284'
370
- """
371
-
348
+ 'False: 0.716, True: 0.284'"""
372
349
Q = ProbDist (X ) # empty probability distribution for X
373
350
for xi in bn .variable_values (X ):
374
351
Q [xi ] = enumerate_all (bn .variables (), extend (e , X , xi ), bn )
@@ -487,7 +464,6 @@ def rejection_sampling (X, e, bn, N):
487
464
>>> p.show_approx()
488
465
'False: 0.7, True: 0.3'
489
466
"""
490
-
491
467
counts = {True : 0 , False : 0 } # boldface N in Fig. 14.13
492
468
493
469
for j in xrange (N ):
@@ -542,7 +518,6 @@ def likelihood_weighting (X, e, bn, N):
542
518
>>> p.show_approx()
543
519
'False: 0.702, True: 0.298'
544
520
"""
545
-
546
521
weights = {True : 0.0 , False : 0.0 } # boldface W in Fig. 14.14
547
522
548
523
for j in xrange (N ):
0 commit comments