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

Skip to content

Commit b3ecb33

Browse files
committed
Fixed: enumerate_joint_ask would raise KeyError on a combo of var values that didn't happen to be set. Though maybe this is too lenient, catching KeyError in ProbDist.__getitem__? (instead of in JointProbDist)
1 parent 16563c3 commit b3ecb33

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

probability.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,8 @@ def __init__(self, varname='?', freqs=None):
4747

4848
def __getitem__(self, val):
4949
"Given a value, return P(value)."
50-
return self.prob[val]
50+
try: return self.prob[val]
51+
except KeyError: return 0
5152

5253
def __setitem__(self, val, p):
5354
"Set P(val) = p"
@@ -91,7 +92,8 @@ def __init__(self, variables):
9192

9293
def __getitem__(self, values):
9394
"Given a tuple or dict of values, return P(values)."
94-
return self.prob[event_values(values, self.variables)]
95+
values = event_values(values, self.variables)
96+
return ProbDist.__getitem__(self, values)
9597

9698
def __setitem__(self, values, p):
9799
"""Set P(values) = p. Values can be a tuple or a dict; it must
@@ -114,13 +116,12 @@ def __repr__(self):
114116

115117
def enumerate_joint_ask(X, e, P):
116118
"""Return a probability distribution over the values of the variable X,
117-
given the {var:val} observations e, in the JointProbDist P.
118-
Works for Boolean variables only. [Fig. 13.4].
119-
120-
X is a string (variable name).
121-
e is a dictionary of variable-name value pairs.
122-
P is an instance of JointProbDist."""
123-
119+
given the {var:val} observations e, in the JointProbDist P. [Fig. 13.4]
120+
>>> P = JointProbDist(['X', 'Y'])
121+
>>> P[0,0] = 0.25; P[0,1] = 0.5; P[1,1] = P[2,1] = 0.125
122+
>>> enumerate_joint_ask('X', dict(Y=1), P).show_approx()
123+
'0: 0.667, 1: 0.167, 2: 0.167'
124+
"""
124125
Q = ProbDist(X) # probability distribution for X, initially empty
125126
Y = [v for v in P.variables if v != X and v not in e] # hidden vars.
126127
for xi in P.values(X):

0 commit comments

Comments
 (0)