Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion aima/learning.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 5 additions & 1 deletion aima/probability.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
16 changes: 16 additions & 0 deletions tests/test_learning.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
6 changes: 5 additions & 1 deletion tests/test_mdp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion tests/test_probability.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})


Expand Down
Loading