@@ -200,46 +200,42 @@ def __init__(self, X, parents, cpt):
200
200
P(X=true | parent=v) = p. When there's just one parent.
201
201
202
202
* A dict {(v1, v2, ...): p, ...}, the distribution P(X=true |
203
- parent1=v1, parent2=v2, ...) = p. You can use this form
204
- always; the first two are just conveniences.
203
+ parent1=v1, parent2=v2, ...) = p. Each key must have as many
204
+ values as there are parents. You can use this form always;
205
+ the first two are just conveniences.
205
206
206
207
In all cases the probability of X being false is left implicit,
207
208
since it follows from P(X=true).
208
209
209
210
>>> X = BayesNode('X', '', 0.2)
210
211
>>> Y = BayesNode('Y', 'P', {T: 0.2, F: 0.7})
211
212
>>> Z = BayesNode('Z', 'P Q',
212
- ... {(T, T): 0.2, (T, F): 0.3, (F, T): 0.5, (F, F): 0.7})"""
213
+ ... {(T, T): 0.2, (T, F): 0.3, (F, T): 0.5, (F, F): 0.7})
214
+ """
213
215
if isinstance (parents , str ): parents = parents .split ()
214
216
215
217
# We store the table always in the third form above.
216
218
if isinstance (cpt , (float , int )): # no parents, 0-tuple
217
219
cpt = {(): cpt }
218
220
elif isinstance (cpt , dict ):
219
- if cpt : key = cpt .keys ()[0 ]
220
- else : key = None
221
- if isinstance (key , bool ): # one parent, 1-tuple
221
+ if cpt and isinstance (cpt .keys ()[0 ], bool ): # one parent, 1-tuple
222
222
cpt = dict (((k ,), v ) for k , v in cpt .items ())
223
- elif isinstance ( key , tuple ): # normal case, n-tuple
224
- pass
225
- else :
226
- raise Exception ( "wrong key type: %s" % cpt )
227
- else :
228
- raise Exception ( "wrong table type: %s" % cpt )
223
+
224
+ assert isinstance ( cpt , dict )
225
+ for vs , p in cpt . items () :
226
+ assert isinstance ( vs , tuple ) and len ( vs ) == len ( parents )
227
+ assert every ( lambda v : isinstance ( v , bool ), vs )
228
+ assert 0 <= p <= 1
229
229
230
230
update (self , variable = X , parents = parents , cpt = cpt )
231
231
232
232
def p (self , value , event ):
233
233
"""Return the conditional probability
234
234
P(X=value | parents = parent_values), where parent_values
235
- are the values of parents in event.
236
-
237
- Preconditions:
238
- 1. each variable in parents is bound to a value in event.
239
- in which they are listed in the CPT.
240
- XXX fix doctest
241
- >> event = {'Burglary': False, 'Earthquake': True}
242
- >> BoolCPT({T: 0.2, F: 0.625}).p(False, ['Burglary'], event)
235
+ are the values of parents in event. (event must assign each
236
+ parent a value.)
237
+ >>> bn = BayesNode('X', 'Burglary', {T: 0.2, F: 0.625})
238
+ >>> bn.p(False, {'Burglary': False, 'Earthquake': True})
243
239
0.375"""
244
240
assert isinstance (value , bool )
245
241
ptrue = self .cpt [event_values (event , self .parents )]
0 commit comments