AdaptiveRandomForestClassifier: replace the trees that go wrong¶
A first example: payments whose rule changes¶
Half of the payments are fraud. At first a fraud is a large payment (around 400) and a normal one is small (around 60); after 750 payments they swap. A forest of 5 trees predicts each payment before it learns it. The first line is the accuracy on payments 500 to 750, on the 100 payments after the change and on the last 200; the second line is the number of warnings and of drifts that the detectors of the trees raised.
import numpy as np
from dense_armor.core.online.forest import AdaptiveRandomForestClassifier
rng = np.random.default_rng(0)
forest = AdaptiveRandomForestClassifier(n_models=5, seed=1)
hits = []
for i in range(1500):
fraud = int(rng.random() < 0.5)
big = fraud if i < 750 else 1 - fraud
amount = float(rng.normal(400 if big else 60, 40 if big else 15))
hits.append(forest.predict_one({"amount": amount}) == fraud)
forest.learn_one({"amount": amount}, fraud)
h = np.array(hits, float)
print(h[500:750].mean().round(3), h[750:850].mean().round(3), h[1300:].mean().round(3))
print(forest.n_warnings_, forest.n_drifts_)
Each tree has two detectors fed with its own mistakes: a warning starts a replacement tree in the background, and a drift puts the replacement in place of the old tree. The accuracy falls a little after the change (to the second number of the first line) and comes back, while the trees that went wrong are replaced.
How it works¶
AdaptiveRandomForestClassifier is the forest of Gomes and colleagues (2017). It has four ideas, each one simple.
Every tree sees every sample, but with a random weight: a sample counts as many times as a Poisson draw with mean 6, so no two trees train on the same data. Every tree also looks at only a few randomly chosen features when it considers a split, which makes the trees differ from one another. Every tree has two small detectors fed with its own mistakes: a warning detector, which is easy to trigger, and a drift detector, which needs more evidence. A warning starts a second tree in the background that trains on the stream but does not vote. If the drift detector then fires, the background tree takes the place of the old one. Finally the forest votes, and each tree's vote is weighted by its recent accuracy.
import numpy as np
from dense_armor.core.online.forest import AdaptiveRandomForestClassifier
rng = np.random.default_rng(0)
f = AdaptiveRandomForestClassifier(n_models=5, seed=1)
for i in range(1500):
x = float(rng.normal(0.0 if rng.random() < 0.5 else 5.0, 0.4))
y = int(x > 2.5) if i < 750 else int(x <= 2.5)
f.learn_one({"x": x}, y)
print(f.predict_one({"x": 0.1}), f.predict_one({"x": 5.0}))
print(f.n_warnings_, f.n_drifts_)
The stream gives class 0 to small x for the first 750 samples and then swaps the two labels. After the swap the forest answers 1 for x = 0.1 and 0 for x = 5.0, so it has followed the change. Along the way the detectors raised 11 warnings and 3 drifts.
Following a sudden change¶
A longer test makes the effect visible. DriftStream produces four numbers per sample and changes its rule at sample 1000. The change of this generator does not always make an old rule wrong, so the five seeds are the first ones (2, 3, 6, 10 and 12) for which a tree that learns until the change and then stops is wrong after it, with an accuracy below 0.5 (benchmarks/_drift_seeds.py). The figure shows the accuracy over the last 50 samples, as the median of the five seeds, for one adaptive Hoeffding tree and for the forest of ten trees.

Both fall when the rule changes and both come back to 1.0. In the median of the five seeds the forest is right 0.94 of the time in the first 100 samples after the change and the single tree 0.74. Seed by seed the forest scores 0.94, 0.93, 0.93, 0.94 and 0.95 and the tree 0.94, 0.76, 0.74, 0.10 and 0.62: the forest is better on four seeds and equal on one, with a paired one-sided Wilcoxon p = 0.062, not below 0.05 (with five seeds the smallest value it can take is 0.031).
The detectors tell the same story from the inside. The next figure counts, for the first seed (2), how many warnings and drifts the ten trees raised.

Before the change there is no warning and no drift. After it the ten trees raised 10 warnings and no drift: a warning alone starts a background tree and replaces nothing, so on this seed no tree was replaced. Over the five seeds the totals are 10, 18, 18, 12 and 0 warnings and 0, 0, 7, 3 and 0 drifts; on the last seed the detectors raised nothing and the forest was right on 0.95 of the first 100 samples after the change. Slower detectors, passed as drift_detector and warning_detector, trade reaction time for fewer false replacements.
The forest costs about 0.97 ms per sample for ten trees against 0.11 ms for the single tree, roughly nine times more.
The parameters¶
| Parameter | Meaning | Default |
|---|---|---|
n_models |
number of trees | 10 |
max_features |
features tried per split attempt; None takes int(sqrt(M)) + 1 |
None |
lambda_ |
mean of the Poisson weight of a sample for a tree | 6.0 |
drift_detector |
template of the drift detector, cloned for every tree; None takes ADWIN(delta=0.001) |
None |
warning_detector |
template of the warning detector; None takes ADWIN(delta=0.01) |
None |
seed |
seed of the Poisson weights and of the feature subsets | None |
grace_period |
samples at a leaf before a split is attempted | 50 |
API reference¶
arf ¶
Adaptive Random Forest classifier for evolving data streams.
Page numbers below are PDF page indices of the paper's PDF, not the printed page numbers of the journal.
A forest of Hoeffding trees, each trained on a Poisson-weighted copy of the stream and each watched by its own pair of change detectors, after Gomes et al. (2017). A single Hoeffding tree follows a change through one detector; the forest follows it through one detector per tree, and the spread of the votes says how sure it is.
The pieces, with the place where the paper states them (page numbers are those of the PDF):
- Online bagging. Every tree sees every sample
ktimes, withk ~ Poisson(lambda_)(Algorithm 1, page 7). The paper useslambda_ = 6, as in leveraging bagging, instead of 1. - Random subspace. When a node is created, a random subset of
mfeatures is drawn and only they are tried at that node's split attempts (Algorithm 1 and the text below it, page 7). The paper usesm = sqrt(M) + 1forMfeatures (page 15). - One warning detector and one drift detector per tree, fed with the test-then-train error of the tree (Algorithm 2, page 8). A warning starts a background tree that is trained but does not vote; a drift replaces the tree by its background tree.
- Background trees carry no detectors, so they cannot start further background trees (page 9).
- The vote of a tree is weighted by
c / n:nsamples seen since its last reset andcof them classified correctly (page 8).
Choices the paper does not fix, stated as my choice:
- The detector thresholds. The paper compares a slow setting
(
delta_w = 1e-4,delta_d = 1e-5) with a fast one (delta_w = 0.01,delta_d = 0.001) on page 17. Without detectors given, this class takes the fast setting, because it reacts inside streams of a few thousand samples. - The subset of features of a node is drawn at the first split attempt of the node, from the features seen there, and kept for the later attempts; the paper draws it at creation, when a streaming tree does not yet know its features.
- A drift without a warning before it replaces the tree by a new empty tree, since there is no background tree to promote.
- The vote adds the class probabilities of each tree, times its weight, and normalises; the paper weights the class votes. When every weight is zero, as before any tree has been scored, all trees count equally.
- A sample for which a tree has no answer yet counts as an error for that tree.
Examples:
>>> import numpy as np
>>> from dense_armor.core.online.forest.arf import AdaptiveRandomForestClassifier
>>> rng = np.random.default_rng(0)
>>> arf = AdaptiveRandomForestClassifier(n_models=5, seed=1)
>>> for _ in range(600):
... x = float(rng.normal(0.0 if rng.random() < 0.5 else 5.0, 0.4))
... _ = arf.learn_one({"x": x}, 0 if x < 2.5 else 1)
>>> arf.predict_one({"x": 0.1}), arf.predict_one({"x": 5.0})
(0, 1)
References
Gomes, H. M., Bifet, A., Read, J., Barddal, J. P., Enembreck, F., Pfahringer, B., Holmes, G., Abdessalem, T. (2017). Adaptive random forests for evolving data stream classification. Machine Learning 106, 1469-1495. Algorithm 1 (page 7), Algorithm 2 (page 8), Section 4 (pages 8-9).
SubspaceHoeffdingTree ¶
SubspaceHoeffdingTree(
grace_period: int = 200,
delta: float = 1e-07,
tau: float = 0.05,
max_depth: int | None = None,
max_nodes: int | None = None,
leaf: str = "nb",
max_features: int | None = None,
seed: int | None = None,
criterion: str = "entropy",
splitter: str = "class_means",
n_splits: int = 10,
nominal_attributes: Any = None,
max_active_leaves: int | None = 1000,
memory_period: int = 1000,
quantile_radius: float | None = None,
)
Bases: HoeffdingTreeClassifier
Hoeffding tree whose split attempts see a random subset of features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grace_period
|
int
|
samples at a leaf before a split is attempted. |
200
|
delta
|
float
|
one minus the confidence of the Hoeffding bound. |
1e-07
|
tau
|
float
|
tie threshold. |
0.05
|
max_depth
|
int | None
|
maximum depth, or |
None
|
max_nodes
|
int | None
|
maximum number of nodes per tree, or |
None
|
leaf
|
str
|
|
'nb'
|
criterion
|
str
|
as in :class: |
'entropy'
|
max_features
|
int | None
|
size |
None
|
seed
|
int | None
|
seed of the generator that draws the subsets. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
on a non-positive |
Source code in dense_armor/core/online/forest/arf.py
AdaptiveRandomForestClassifier ¶
AdaptiveRandomForestClassifier(
n_models: int = 10,
max_features: int | None = None,
lambda_: float = 6.0,
drift_detector: DriftDetector | None = None,
warning_detector: DriftDetector | None = None,
seed: int | None = None,
grace_period: int = 50,
)
Bases: Classifier
Adaptive Random Forest of Gomes et al. (2017).
Each of the n_models trees is a :class:SubspaceHoeffdingTree.
On every sample each tree is scored on the sample before learning
it, trained Poisson(lambda_) times on it, and its error (0 or
1) goes to its warning detector and its drift detector. The forest
answers with the weighted vote of the trees.
A warning creates a background tree for that member; a drift replaces the member's tree by the background tree, resets the member's score and its detectors.
Cost and memory. learn_one does n_models predictions, about
n_models * lambda_ tree updates and 2 * n_models detector
updates; predict_one does n_models predictions. The statistics
of each tree are bounded by its max_active_leaves (the least
promising leaves are deactivated), so they are constant in the
stream length and linear in n_models and in the number of
features; the number of nodes follows the data unless max_nodes
or max_depth is set. There is no pure init_state / step form: the state
is a set of trees of changing shape, which a jax.lax.scan cannot
carry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_models
|
int
|
number of trees. Default 10. |
10
|
max_features
|
int | None
|
features tried per split attempt. |
None
|
lambda_
|
float
|
mean of the Poisson weight. Default 6.0 (the paper). |
6.0
|
drift_detector
|
DriftDetector | None
|
template of the drift detector, cloned for every
tree. |
None
|
warning_detector
|
DriftDetector | None
|
template of the warning detector, cloned for
every tree. |
None
|
seed
|
int | None
|
seed of the generator of the Poisson weights and of the feature subsets. |
None
|
grace_period
|
int
|
samples at a leaf before a split is attempted (my choice: 50, shorter than the tree default of 200, so that trees grow within streams of a few thousand samples). |
50
|
Raises:
| Type | Description |
|---|---|
ValueError
|
on a non-positive |
Examples:
>>> from dense_armor.core.online.forest.arf import AdaptiveRandomForestClassifier
>>> arf = AdaptiveRandomForestClassifier(n_models=3, seed=0)
>>> arf.predict_one({"x": 0.0}) is None
True
>>> for i in range(100):
... _ = arf.learn_one({"x": float(i % 2)}, i % 2)
>>> arf.predict_one({"x": 1.0})
1
References
Gomes et al. (2017), Machine Learning 106, 1469-1495, Algorithm 1 (page 7) and Algorithm 2 (page 8).
Source code in dense_armor/core/online/forest/arf.py
learn_one ¶
Score, train and watch every tree on one sample.
A sample that is empty, has a missing or non-finite value, or
has no label is skipped and counted in n_missing.
Source code in dense_armor/core/online/forest/arf.py
predict_proba_one ¶
Weighted vote of the class probabilities of the trees.
Source code in dense_armor/core/online/forest/arf.py
predict_one ¶
Return the class with the largest weighted vote, or None.
Source code in dense_armor/core/online/forest/arf.py
Details¶
The references, the choices the papers do not fix, the checks, the cost and the memory of the forests are in the Details of Streaming forests.