Skip to content

Hoeffding Adaptive tree: it follows a change

When the world changes suddenly (a different load, a worn joint) a tree built on the old data keeps giving the old answers. HoeffdingAdaptiveTreeClassifier puts a drift detector on every internal node; when the error of a node jumps, it grows an alternative subtree in the background and swaps it in once the new one is clearly better.

Gamestory

New Year's Eve in London. A mysterious thief is emptying the banks of the city.

The young detective keeps a notebook with his theory: "the thief strikes the banks with the richest vaults". For the first half of the night it works. A stubborn detective (the plain Hoeffding tree) would keep the same theory until dawn: when the thief starts to strike only the poorest banks, he would be wrong every single time and would never notice.

Our detective reasons like a Hoeffding Adaptive tree. Next to every question of his theory there is a small alarm that counts how often that question is wrong. When an alarm rings, he does not throw the theory away: he opens a second notebook in the background, with the new clues, and goes on acting on the old one. He compares the two notebooks on the same cases, and as soon as the new one is clearly better he swaps them. Only the part of the theory that failed is replaced; everything else stays.

1. When the meaning of an amount changes

A fraud team watches card payments, half of them fraud. At first a fraud is a large payment (around 400) and a normal payment is small (around 60). After 3000 payments the fraudsters change habit: they now make small test charges, while the customers' payments grow. The meaning of the amount flips. Each payment is first predicted and then learned, and the accuracy is counted on the 3000 payments after the change.

import numpy as np
from dense_armor.core.evaluation.metrics import Accuracy
from dense_armor.core.online.drift.adwin import ADWIN
from dense_armor.core.online.tree import HoeffdingAdaptiveTreeClassifier, HoeffdingTreeClassifier

rng = np.random.default_rng(0)
plain = HoeffdingTreeClassifier(grace_period=100)
adaptive = HoeffdingAdaptiveTreeClassifier(grace_period=100, drift_detector=ADWIN())
acc_plain, acc_adaptive = Accuracy(), Accuracy()
for i in range(6000):
    fraud = int(rng.random() < 0.5)
    big = fraud if i < 3000 else 1 - fraud
    x = {"amount": rng.normal(400 if big else 60, 60 if big else 20), "hour": rng.normal(14, 3)}
    if i >= 3000:
        acc_plain.update(fraud, plain.predict_one(x))
        acc_adaptive.update(fraud, adaptive.predict_one(x))
    plain.learn_one(x, fraud)
    adaptive.learn_one(x, fraud)
print(round(acc_plain.get(), 3), round(acc_adaptive.get(), 3), adaptive.n_drifts_, adaptive.n_swaps_)
0.044 0.964 3 1

After the change the plain tree is right 4.4 % of the time: it keeps the old rule, so it is wrong almost every time. The adaptive tree is right 96.4 % of the time: its alarm rang 3 times (n_drifts_) and it swapped in the new subtree once (n_swaps_). The next sections show the same behaviour on a robot arm, with the figure of what happens sample by sample.

2. A robot arm after a sudden change

After 3000 samples the meaning of the torque flips (the load is now the low-torque state). The same split on tau still separates the two states, but the answers are swapped. The adaptive tree watches its own error with a drift detector (ADWIN) on each node; when the error jumps, it grows a second subtree in the background and swaps it in when that subtree is clearly more accurate.

import numpy as np
from dense_armor.core.online.drift.adwin import ADWIN
from dense_armor.core.evaluation.metrics import Accuracy
from dense_armor.core.online.tree import HoeffdingAdaptiveTreeClassifier, HoeffdingTreeClassifier

rng = np.random.default_rng(1)
ht = HoeffdingTreeClassifier(grace_period=100)
hat = HoeffdingAdaptiveTreeClassifier(grace_period=100, drift_detector=ADWIN())
acc_ht, acc_hat = Accuracy(), Accuracy()
for i in range(6000):
    y = int(rng.random() < 0.5)
    c = 3.0 * y if i < 3000 else 3.0 * (1 - y)
    x = {"tau": rng.normal(2.0 + c, 0.5), "qd": rng.normal(0.0, 1.0)}
    if i >= 3000:
        acc_ht.update(y, ht.predict_one(x))
        acc_hat.update(y, hat.predict_one(x))
    ht.learn_one(x, y)
    hat.learn_one(x, y)
print(round(acc_ht.get(), 3), round(acc_hat.get(), 3), hat.n_drifts_, hat.n_swaps_)
0.056 0.95 3 1

Plain and adaptive Hoeffding tree under a sudden change at sample 3000: the plain tree falls to zero accuracy, the adaptive tree dips to 0.47, swaps in its background subtree at sample 3103 and is back at 1.0 by sample 3300.

Over the 3000 samples after the change, the plain tree is right 5.6 % of the time (it keeps the old answers); the adaptive tree detected the change (3 drift signals), swapped in its background subtree once, and is right 95 % of the time. The swap test compares the errors of the two subtrees counted on the same samples since the background one started, and swaps when the difference exceeds \(\sqrt{\ln(2/\delta)/n}\) after at least kappa_alt samples.

In the figure the pink ticks are the three drift signals (samples 3004, 3007 and 3010, a few samples after the change) and the cyan tick is the swap, at sample 3103, once the background subtree had been better for kappa_alt samples. The accuracy is the one over the last 200 predictions, so it falls over about 100 samples even for an instant change; the plain tree reaches zero, because every answer is now the wrong one, and starts to recover only near the end of the stream.

API reference

adaptive

Hoeffding Adaptive Tree classifier.

The Hoeffding tree never revisits a split. The Hoeffding Adaptive Tree (HAT) of Bifet and Gavalda (2009) adds a drift detector at each node: when the detector warns, an alternate subtree grows in the background on the recent samples; when the alternate is significantly more accurate than the main one, it replaces the corresponding branch.

The detector and the error counters live on the node, not in a dict keyed by id(node), so clone, pickle and state round-trips work.

Examples:

>>> import numpy as np
>>> from dense_armor.core.online.drift.adwin import ADWIN
>>> from dense_armor.core.online.tree.adaptive import HoeffdingAdaptiveTreeClassifier
>>> rng = np.random.default_rng(0)
>>> h = HoeffdingAdaptiveTreeClassifier(
...     grace_period=30, drift_detector=ADWIN()
... )
>>> for _ in range(400):
...     x = float(rng.normal(0.0 if rng.random() < 0.5 else 5.0, 0.4))
...     y = 0 if x < 2.5 else 1
...     _ = h.learn_one({"x": x}, y=y)
>>> h.predict_one({"x": 0.1}) != h.predict_one({"x": 5.0})
True
References

Bifet, A., Gavalda, R. (2009). Adaptive learning from evolving data streams. In IDA. Esteban, A., Cano, A., Zafra, A., Ventura, S. (2024). Hoeffding adaptive trees for multi-label classification on data streams. Domingos, P., Hulten, G. (2000). Mining high-speed data streams. In KDD.

HoeffdingAdaptiveTreeClassifier

HoeffdingAdaptiveTreeClassifier(
    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",
    drift_detector: DriftDetector | None = None,
    delta_alt: float = 0.01,
    kappa_alt: int = 100,
    error_alpha: float = 0.005,
    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 Adaptive Tree classifier.

Memory grows with the number of nodes of the main tree and of any alternate subtrees; max_nodes (default None) can bound the total.

budget_s = 5e-3 s: p99 of learn_one measured at 3.7e-4 s on a 2000-sample, two-feature stream on a desktop CPU (default parameters); the budget leaves room for slower machines.

Parameters:

Name Type Description Default
grace_period int

minimum samples at a node before a split attempt.

200
delta float

one minus the confidence of the Hoeffding bound for splits.

1e-07
tau float

tie threshold.

0.05
max_depth int | None

maximum depth, or None.

None
max_nodes int | None

maximum number of nodes, or None (default).

None
leaf str

"nb" or "majority".

'nb'
criterion str

"entropy" or "gini", as in :class:HoeffdingTreeClassifier.

'entropy'
splitter str

numeric splitter, as in :class:HoeffdingTreeClassifier.

'class_means'
n_splits int

candidate thresholds of the "gaussian" splitter.

10
nominal_attributes Any

categorical features, as in :class:HoeffdingTreeClassifier.

None
max_active_leaves int | None

leaves that keep statistics, as in :class:HoeffdingTreeClassifier.

1000
memory_period int

samples between two memory checks.

1000
quantile_radius float | None

slot width of the "quantile" splitter.

None
drift_detector DriftDetector | None

a fresh DriftDetector instance, cloned per node.

None
delta_alt float

one minus the confidence of the alternate bound.

0.01
kappa_alt int

minimum samples for an alternate to be considered.

100
error_alpha float

smoothing of the per-node error estimate.

0.005

Raises:

Type Description
ValueError

on a bad leaf or a non-positive parameter.

Source code in dense_armor/core/online/tree/adaptive.py
def __init__(
    self,
    grace_period: int = 200,
    delta: float = 1e-7,
    tau: float = 0.05,
    max_depth: int | None = None,
    max_nodes: int | None = None,
    leaf: str = "nb",
    drift_detector: DriftDetector | None = None,
    delta_alt: float = 0.01,
    kappa_alt: int = 100,
    error_alpha: float = 0.005,
    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,
) -> None:
    super().__init__(
        grace_period=grace_period,
        delta=delta,
        tau=tau,
        max_depth=max_depth,
        max_nodes=max_nodes,
        leaf=leaf,
        criterion=criterion,
        splitter=splitter,
        n_splits=n_splits,
        nominal_attributes=nominal_attributes,
        max_active_leaves=max_active_leaves,
        memory_period=memory_period,
        quantile_radius=quantile_radius,
    )
    if drift_detector is None:
        raise ValueError("drift_detector is required")
    if not 0.0 < delta_alt < 1.0:
        raise ValueError(f"delta_alt must be in (0, 1), got {delta_alt}")
    if kappa_alt < 1:
        raise ValueError(f"kappa_alt must be >= 1, got {kappa_alt}")
    if not 0.0 < error_alpha <= 1.0:
        raise ValueError(f"error_alpha must be in (0, 1], got {error_alpha}")
    self.drift_detector = drift_detector
    self.delta_alt = delta_alt
    self.kappa_alt = kappa_alt
    self.error_alpha = error_alpha
    self.n_drifts_ = 0
    self.n_alt_starts_ = 0
    self.n_swaps_ = 0

Details

  • Adaptive tree: a detector on each internal node (default ADWIN, cloned per node); swap and discard are decided only after kappa_alt (100) samples of the background subtree, on errors counted on the same samples. As in Esteban et al. (2024), the detectors sit on the internal nodes.
  • The detector is any DriftDetector of the library (default ADWIN); see drift detection.
  • Sources: Esteban, A., Cano, A., Zafra, A., Ventura, S. (2024), "Hoeffding adaptive trees for multi-label classification on data streams", arXiv:2410.20242.