Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8e39013

Browse files
committed
Make BayesNet create its BayesNodes, so they can't possibly be shared. (Avoids bug that bit me.)
1 parent 2966301 commit 8e39013

File tree

1 file changed

+17
-18
lines changed

1 file changed

+17
-18
lines changed

probability.py

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -147,16 +147,17 @@ def enumerate_joint(vars, e, P):
147147
class BayesNet:
148148
"Bayesian network containing only boolean-variable nodes."
149149

150-
def __init__(self, nodes=[]):
150+
def __init__(self, node_specs=[]):
151151
"nodes must be ordered with parents before children."
152152
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)
155155

156-
def add(self, node):
156+
def add(self, node_spec):
157157
"""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
160161
assert every(lambda parent: parent in self.vars, node.parents)
161162
self.nodes.append(node)
162163
self.vars.append(node.variable)
@@ -244,21 +245,19 @@ def sample(self, event):
244245
return probability(self.p(True, event))
245246

246247
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)))
250249

251250
# Burglary example [Fig. 14.2]
252251

253252
T, F = True, False
254253

255254
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',
259258
{(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})
262261
])
263262

264263
#______________________________________________________________________________
@@ -377,10 +376,10 @@ def all_events(vars, bn, e):
377376
# Fig. 14.12a: sprinkler network
378377

379378
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',
384383
{(T, T): 0.99, (T, F): 0.90, (F, T): 0.90, (F, F): 0.00})])
385384

386385
#______________________________________________________________________________

0 commit comments

Comments
 (0)