@@ -147,16 +147,17 @@ def enumerate_joint(vars, e, P):
147
147
class BayesNet :
148
148
"Bayesian network containing only boolean-variable nodes."
149
149
150
- def __init__ (self , nodes = []):
150
+ def __init__ (self , node_specs = []):
151
151
"nodes must be ordered with parents before children."
152
152
update (self , nodes = [], vars = [])
153
- for node in nodes :
154
- self .add (node )
153
+ for node_spec in node_specs :
154
+ self .add (node_spec )
155
155
156
- def add (self , node ):
156
+ def add (self , node_spec ):
157
157
"""Add a node to the net. Its parents must already be in the
158
- net, and node itself must not."""
159
- assert node not in self .nodes
158
+ net, and its variable must not."""
159
+ node = BayesNode (* node_spec )
160
+ assert node .variable not in self .vars
160
161
assert every (lambda parent : parent in self .vars , node .parents )
161
162
self .nodes .append (node )
162
163
self .vars .append (node .variable )
@@ -244,21 +245,19 @@ def sample(self, event):
244
245
return probability (self .p (True , event ))
245
246
246
247
def __repr__ (self ):
247
- return 'node(%r, %r)' % (self .variable , ' ' .join (self .parents ))
248
-
249
- node = BayesNode
248
+ return repr ((self .variable , ' ' .join (self .parents )))
250
249
251
250
# Burglary example [Fig. 14.2]
252
251
253
252
T , F = True , False
254
253
255
254
burglary = BayesNet ([
256
- node ('Burglary' , '' , 0.001 ),
257
- node ('Earthquake' , '' , 0.002 ),
258
- node ('Alarm' , 'Burglary Earthquake' ,
255
+ ('Burglary' , '' , 0.001 ),
256
+ ('Earthquake' , '' , 0.002 ),
257
+ ('Alarm' , 'Burglary Earthquake' ,
259
258
{(T , T ): 0.95 , (T , F ): 0.94 , (F , T ): 0.29 , (F , F ): 0.001 }),
260
- node ('JohnCalls' , 'Alarm' , {T : 0.90 , F : 0.05 }),
261
- node ('MaryCalls' , 'Alarm' , {T : 0.70 , F : 0.01 })
259
+ ('JohnCalls' , 'Alarm' , {T : 0.90 , F : 0.05 }),
260
+ ('MaryCalls' , 'Alarm' , {T : 0.70 , F : 0.01 })
262
261
])
263
262
264
263
#______________________________________________________________________________
@@ -377,10 +376,10 @@ def all_events(vars, bn, e):
377
376
# Fig. 14.12a: sprinkler network
378
377
379
378
sprinkler = BayesNet ([
380
- node ('Cloudy' , '' , 0.5 ),
381
- node ('Sprinkler' , 'Cloudy' , {T : 0.10 , F : 0.50 }),
382
- node ('Rain' , 'Cloudy' , {T : 0.80 , F : 0.20 }),
383
- node ('WetGrass' , 'Sprinkler Rain' ,
379
+ ('Cloudy' , '' , 0.5 ),
380
+ ('Sprinkler' , 'Cloudy' , {T : 0.10 , F : 0.50 }),
381
+ ('Rain' , 'Cloudy' , {T : 0.80 , F : 0.20 }),
382
+ ('WetGrass' , 'Sprinkler Rain' ,
384
383
{(T , T ): 0.99 , (T , F ): 0.90 , (F , T ): 0.90 , (F , F ): 0.00 })])
385
384
386
385
#______________________________________________________________________________
0 commit comments