diff --git a/aima/learning.py b/aima/learning.py index c8c19ba57..129786801 100644 --- a/aima/learning.py +++ b/aima/learning.py @@ -1153,9 +1153,12 @@ def feature_bagging(dataset, p=0.7): def predict(example): return mode(predictor(example) for predictor in predictors) + # each sample keeps the domains of the whole data set, or a tree would not + # know the values its sample happens to miss predictors = [DecisionTreeLearner(DataSet(examples=data_bagging(dataset), attrs=dataset.attrs, attr_names=dataset.attr_names, target=dataset.target, - inputs=feature_bagging(dataset))) for _ in range(n)] + inputs=feature_bagging(dataset), + values=dataset.values)) for _ in range(n)] return predict diff --git a/aima/probability.py b/aima/probability.py index 106aa59e5..2945f37e6 100644 --- a/aima/probability.py +++ b/aima/probability.py @@ -68,8 +68,12 @@ def __setitem__(self, val, p): def normalize(self): """Make sure the probabilities of all values sum to 1. Returns the normalized distribution. - Raises a ZeroDivisionError if the sum of the values is 0.""" + Raises a ValueError if the sum of the values is 0, since then there + is no distribution to normalize to.""" total = sum(self.prob.values()) + if total == 0: + raise ValueError('ProbDist.normalize: the probabilities sum to 0, ' + 'so they cannot be normalized') # divide even when the total is close to 1, or the error builds up over # repeated updates (np.isclose would accept totals off by 1e-5) if total != 1: diff --git a/tests/test_learning.py b/tests/test_learning.py index 9a568533e..d07e840b3 100644 --- a/tests/test_learning.py +++ b/tests/test_learning.py @@ -120,6 +120,22 @@ def test_random_forest(): assert grade_learner(rf, tests) >= 1 / 3 +def test_random_forest_keeps_the_domains(monkeypatch): + # the value 2 is rare, so some bootstrap samples miss it + data = DataSet(examples=[[0, 'n']] * 10 + [[1, 'p']] * 9 + [[2, 'p']], attr_names=['a', 'c']) + learned = [] + + def learner(dataset): + learned.append((dataset, DecisionTreeLearner(dataset))) + return learned[-1][1] + + monkeypatch.setattr('aima.learning.DecisionTreeLearner', learner) + random.seed(3) + RandomForest(data, n=20) + assert any(all(e[0] != 2 for e in sample.examples) for sample, _ in learned) + assert all(set(tree.branches) == {0, 1, 2} for _, tree in learned) + + def test_random_forest_does_not_print(capsys): iris = DataSet(name='iris') RandomForest(iris)([5.0, 3.0, 1.0, 0.1]) diff --git a/tests/test_mdp.py b/tests/test_mdp.py index 14dc703f4..b6b07d6b7 100644 --- a/tests/test_mdp.py +++ b/tests/test_mdp.py @@ -46,7 +46,11 @@ def test_value_iteration(): # exact float equality on the value function is brittle across numpy/BLAS # versions (the values can differ in the last decimal), so compare with a # tolerance via pytest.approx - assert value_iteration(sequential_decision_environment, .01) == pytest.approx({ + # the pinned values are those at the stop, within epsilon of the converged ones + U = value_iteration(sequential_decision_environment, .01) + U_star = value_iteration(sequential_decision_environment, 1e-9) + assert all(abs(U[s] - U_star[s]) < .01 for s in U) + assert U == pytest.approx({ (3, 2): 1.0, (3, 1): -1.0, (3, 0): 0.12958868267972745, (0, 1): 0.39810203830605462, (0, 2): 0.50928545646220924, (1, 0): 0.25348746162470537, diff --git a/tests/test_probability.py b/tests/test_probability.py index ac53d9b6a..465957a5b 100644 --- a/tests/test_probability.py +++ b/tests/test_probability.py @@ -836,7 +836,7 @@ def joint(xs): def test_prob_dist_single_value_and_unnormalized(): P = ProbDist('X', {'only': 3}) assert P['only'] == 1 and P['missing'] == 0 - with pytest.raises(ZeroDivisionError): + with pytest.raises(ValueError, match='sum to 0'): ProbDist('Y', {'a': 0, 'b': 0})