Skip to content

OnlineExtraTreesRegressor: draw the split at random

A first example: the cost of an insurance claim

A claim costs 400 more when the amount feature is positive and 100 more when the tenure feature is above 0.5, with a noise of 20; three other features (hour, weekday, channel) have nothing to do with the cost. The forest sees 1500 claims, one at a time, and is asked the cost of three claims, whose true costs are 400, 100 and 500.

import numpy as np
from dense_armor.core.online.forest import OnlineExtraTreesRegressor

rng = np.random.default_rng(0)
forest = OnlineExtraTreesRegressor(n_models=5, seed=0)
names = ["amount", "tenure", "hour", "weekday", "channel"]
for _ in range(1500):
    x = {k: float(rng.uniform(-1.0, 1.0)) for k in names}
    cost = 400.0 * (x["amount"] > 0.0) + 100.0 * (x["tenure"] > 0.5)
    forest.learn_one(x, cost + float(rng.normal(0.0, 20.0)))
rest = {"hour": 0.3, "weekday": -0.2, "channel": 0.9}
print(round(forest.predict_one({"amount": 0.5, "tenure": 0.0, **rest})))
print(round(forest.predict_one({"amount": -0.5, "tenure": 0.8, **rest})))
print(round(forest.predict_one({"amount": 0.5, "tenure": 0.8, **rest})))
394
93
409

The three answers are 394, 93 and 409, for true costs of 400, 100 and 500: the first two are close and the third is 91 below the true cost. The forest never searched for a best split: every leaf drew its split point at random in the range of a small buffer of five observations.

How it works

The random forest and the adaptive random forest ask, for every feature of every leaf, where the best split would be. That is a search: every observed (feature, target) pair is stored, sorted, and scanned. A tree with many leaves, on a stream with many samples, pays for the search at every attempt.

OnlineExtraTreesRegressor (OXT) skips the search. Each leaf draws a small buffer of its first s = 5 observations per candidate feature, takes the minimum and the maximum of that buffer, and picks the split point phi uniformly in that range. From that sample onward, the leaf only keeps two small accumulators, one for the targets below phi and one for the targets above it, and evaluates the variance reduction from those. One candidate per feature, no sorting, no storage of the inputs.

The forest keeps the drift machinery of the adaptive random forest. Every tree sees every sample with probability p = 0.5 (sub-bagging, without replacement). Every tree has two detectors on its own absolute error: a warning, easier to trigger, and a drift, harder. A warning starts a background tree that trains on the same stream but does not vote. If a drift fires, the background tree takes the place of the old one.

import numpy as np
from dense_armor.core.online.forest import OnlineExtraTreesRegressor

rng = np.random.default_rng(0)
f = OnlineExtraTreesRegressor(n_models=5, seed=0)
for _ in range(1500):
    a = float(rng.uniform(-1.0, 1.0))
    b = float(rng.uniform(-1.0, 1.0))
    f.learn_one({"a": a, "b": b}, 4.0 * (a > 0.0))
print(round(f.predict_one({"a": 0.5, "b": 0.0}), 1),
      round(f.predict_one({"a": -0.5, "b": 0.0}), 1))
4.0 0.2

The target is 4 when a > 0 and 0 when a < 0; the feature b never matters. After 1500 samples the forest answers close to 4 on the positive side and close to 0 on the negative side, using only random split points and a buffer of five samples per candidate feature.

What the random split costs and buys

The next figure uses the same DriftStream of the adaptive random forest page, one sudden change at sample 1000, 2000 samples, four features, median of five seeds. The seeds are those of the adaptive random forest page. The line is the median absolute error, smoothed over 50 samples, for OXT, for MondrianForestRegressor with ten trees, and for AMRulesRegressor.

Absolute error of OXT, Mondrian forest and AMRules around a sudden change

All three fall when the rule changes. OXT recovers more slowly than the Mondrian forest, and its error after the change stays above the Mondrian line. Against AMRules the OXT line stays below the AMRules line both before and after the change.

The parameters

Parameter Meaning Default
n_models number of trees 20
p chance that a tree trains on a sample (sub-bagging) 0.5
max_features features tried per split attempt; None takes max(1, int(sqrt(M))) None
buffer_size size s of the buffer of the random splitter 5
grace_period samples between split attempts of a leaf 50
delta split significance of the Hoeffding bound 0.05
tau tie threshold 0.05
drift_detector, warning_detector templates of the two detectors, cloned for every tree; None takes ADWIN(delta=0.001) and ADWIN(delta=0.01) None
fading fading factor of the error that chooses between the target mean and the linear model 0.95
learning_rate step of the delta rule of the linear models 0.01
max_nodes, max_depth largest number of nodes and depth of a tree 1000, None
seed, feature_keys seed of the sampling and of the splits; names of the features None

API reference

oxt

Online Extra Trees regressor (OXT) for data streams.

An ensemble of regression trees whose split points are drawn at random, after Mastelini, Nakano, Vens and de Carvalho. The source read is the chapter on OXT of Mastelini's doctoral thesis (USP, 2023), not the journal article; page numbers below are printed pages of the thesis.

The pieces, as the thesis states them:

  • Training (Algorithm 3, page 109). For every tree and every sample: predict, feed the absolute deviation to a warning detector and a drift detector, start a background tree on a warning, replace the tree by the background tree on a drift, skip the sample for this tree with chance 1 - p (sub-bagging, p = 0.5, page 115), otherwise train the tree and its background tree on it. The prediction is the mean of the trees (page 110).
  • Random splitter (Algorithm 4, page 111). A leaf keeps, for each feature of a random subset of size sqrt(M) (page 110, page 115), a buffer of its first s = 5 observations; the range of the buffer gives a split point phi drawn uniformly in it; from then on only the incremental variance of the target on each side of phi is kept. There is one split candidate per monitored feature.
  • Split attempts every grace_period = 50 samples with the split significance delta = 0.05; the pre-pruning test is disabled (page 115).
  • Detectors: ADWIN with confidence 0.01 for the warning and 0.001 for the drift, on the absolute deviation (pages 109 and 114).
  • Leaves predict with the target mean or a linear model, whichever has the lower faded error, with fading factor 0.95 (page 114). 20 trees in the experiments (page 115).

Stated as my choice, because the passages read do not give them:

  • The merit of a candidate is the variance reduction of Equation 4.1 of the thesis (chapter 4), written as (n_le * n_gt / n^2) * (mean_le - mean_gt)^2. The thesis says that Hoeffding trees use the Hoeffding bound to decide when to split but does not print the test; the one used is the ratio of the second best merit to the best one against 1 - eps, with the Hoeffding bound eps = sqrt(ln(1/delta) / (2 n)), or eps < tau with tau = 0.05. The children start from the target statistics of the two sides of the split.
  • The linear model of a leaf works on standardised features and target, starts from zero weights and learns by the delta rule with step 0.01.
  • A drift with no warning before it replaces the tree by an empty one.
  • max_nodes and max_depth bound a tree; the thesis states no limit.
  • The size of the feature subset is max(1, int(sqrt(M))).

Examples:

>>> import numpy as np
>>> from dense_armor.core.online.forest.oxt import OnlineExtraTreesRegressor
>>> rng = np.random.default_rng(0)
>>> model = OnlineExtraTreesRegressor(n_models=5, seed=0)
>>> for _ in range(1500):
...     a = float(rng.uniform(-1.0, 1.0))
...     _ = model.learn_one({"a": a, "b": float(rng.uniform(-1.0, 1.0))}, 4.0 * (a > 0.0))
>>> round(model.predict_one({"a": 0.5, "b": 0.0}), 1), round(model.predict_one({"a": -0.5, "b": 0.0}), 1)
(4.0, 0.2)
References

Mastelini, S. M., Nakano, F. K., Vens, C., de Carvalho, A. C. P. L. F. Online extra trees regressor. IEEE Transactions on Neural Networks and Learning Systems 34(10), 6755-6767. Read in: Mastelini, S. M. (2023). Efficient online tree, rule-based and distance-based algorithms. Doctoral thesis, ICMC-USP, chapter 6, Algorithms 3 and 4, Sections 6.4 and 6.5.

OnlineExtraTreesRegressor

OnlineExtraTreesRegressor(
    n_models: int = 20,
    p: float = 0.5,
    max_features: int | None = None,
    buffer_size: int = 5,
    grace_period: int = 50,
    delta: float = 0.05,
    tau: float = 0.05,
    drift_detector: DriftDetector | None = None,
    warning_detector: DriftDetector | None = None,
    fading: float = 0.95,
    learning_rate: float = 0.01,
    max_nodes: int = 1000,
    max_depth: int | None = None,
    seed: int | None = None,
    feature_keys: list | None = None,
)

Bases: Regressor

Online Extra Trees regressor (Mastelini et al.).

Cost and memory. learn_one predicts with every tree, updates two detectors per tree and trains about p * n_models trees (plus their background trees); predict_one descends every tree. A tree has at most max_nodes nodes, a leaf keeps a buffer or two variance estimators for sqrt(M) features, so the state is constant in the length of the stream and linear in n_models and in the number of features. There is no pure init_state / step form: the state is a set of trees of changing shape.

Parameters:

Name Type Description Default
n_models int

number of trees Nt. Default 20.

20
p float

chance that a tree trains on a sample (sub-bagging). Default 0.5.

0.5
max_features int | None

features tried per split attempt. None takes max(1, int(sqrt(M))).

None
buffer_size int

size s of the buffer of the random splitter. Default 5.

5
grace_period int

samples between split attempts of a leaf. Default 50.

50
delta float

split significance of the Hoeffding bound. Default 0.05.

0.05
tau float

tie threshold. Default 0.05.

0.05
drift_detector DriftDetector | None

template of the drift detector, cloned for every tree. None takes ADWIN(delta=0.001).

None
warning_detector DriftDetector | None

template of the warning detector. None takes ADWIN(delta=0.01).

None
fading float

fading factor of the error that chooses between the target mean and the linear model. Default 0.95.

0.95
learning_rate float

step of the delta rule of the linear models. Default 0.01.

0.01
max_nodes int

largest number of nodes of one tree. Default 1000.

1000
max_depth int | None

largest depth of a tree, or None.

None
seed int | None

seed of the generator of the sampling and of the splits.

None
feature_keys list | None

names of the features. None takes the sorted keys of the first sample.

None

Raises:

Type Description
ValueError

on a non-positive n_models, buffer_size, grace_period, max_nodes or max_features, on p outside (0, 1], delta outside (0, 1), fading outside (0, 1), a negative tau, a non-positive learning_rate or max_depth.

Examples:

>>> from dense_armor.core.online.forest.oxt import OnlineExtraTreesRegressor
>>> model = OnlineExtraTreesRegressor(n_models=3, seed=0)
>>> model.predict_one({"a": 1.0})
0.0
>>> _ = model.learn_one({"a": 1.0}, 2.0)
>>> model.predict_one({"a": 1.0})
1.3333333333333333
References

Mastelini et al., Online extra trees regressor, Algorithms 3 and 4.

Source code in dense_armor/core/online/forest/oxt.py
def __init__(
    self,
    n_models: int = 20,
    p: float = 0.5,
    max_features: int | None = None,
    buffer_size: int = 5,
    grace_period: int = 50,
    delta: float = 0.05,
    tau: float = 0.05,
    drift_detector: DriftDetector | None = None,
    warning_detector: DriftDetector | None = None,
    fading: float = 0.95,
    learning_rate: float = 0.01,
    max_nodes: int = 1000,
    max_depth: int | None = None,
    seed: int | None = None,
    feature_keys: list | None = None,
) -> None:
    if n_models < 1 or buffer_size < 1 or grace_period < 1 or max_nodes < 1:
        raise ValueError(
            "n_models, buffer_size, grace_period and max_nodes must be >= 1"
        )
    if max_features is not None and max_features < 1:
        raise ValueError(f"max_features must be >= 1, got {max_features}")
    if not 0.0 < p <= 1.0:
        raise ValueError(f"p must be in (0, 1], got {p}")
    if not 0.0 < delta < 1.0 or not 0.0 < fading < 1.0:
        raise ValueError("delta and fading must be in (0, 1)")
    if tau < 0.0 or learning_rate <= 0.0:
        raise ValueError("tau must be >= 0 and learning_rate > 0")
    if max_depth is not None and max_depth < 1:
        raise ValueError(f"max_depth must be >= 1, got {max_depth}")
    self.n_models = n_models
    self.p = p
    self.max_features = max_features
    self.buffer_size = buffer_size
    self.grace_period = grace_period
    self.delta = delta
    self.tau = tau
    self.drift_detector = drift_detector
    self.warning_detector = warning_detector
    self.fading = fading
    self.learning_rate = learning_rate
    self.max_nodes = max_nodes
    self.max_depth = max_depth
    self.seed = seed
    self.feature_keys = feature_keys
    self.members_: list = []
    self.n_seen_ = 0
    self.n_missing_ = 0
    self.n_warnings_ = 0
    self.n_drifts_ = 0
    self._keys: list | None = None
    self._rng = np.random.default_rng(seed)

learn_one

learn_one(
    x: Any, y: Any, t: float | None = None
) -> OnlineExtraTreesRegressor

Run Algorithm 3 on one sample.

A sample with a missing or non-finite value or target is skipped and counted in n_missing.

Source code in dense_armor/core/online/forest/oxt.py
def learn_one(
    self, x: Any, y: Any, t: float | None = None
) -> "OnlineExtraTreesRegressor":
    """Run Algorithm 3 on one sample.

    A sample with a missing or non-finite value or target is skipped
    and counted in ``n_missing``.
    """
    self._time_step(t)
    try:
        target = float(y)
    except (TypeError, ValueError):
        target = math.nan
    v = self._vector(x) if math.isfinite(target) else None
    if v is None:
        self.n_missing_ += 1
        return self
    d = len(v)
    if not self.members_:
        self.members_ = [self._member(d) for _ in range(self.n_models)]
    self.n_seen_ += 1
    for m in self.members_:
        err = abs(target - m.tree.predict(v))
        m.warn.update(err)
        m.drift.update(err)
        if m.warn.drift_detected:
            m.background = self._tree(d)
            self.n_warnings_ += 1
        if m.drift.drift_detected:
            m.tree = m.background if m.background is not None else self._tree(d)
            m.background = None
            m.warn = self._detector(self.warning_detector, 0.01)
            m.drift = self._detector(self.drift_detector, 0.001)
            self.n_drifts_ += 1
        if self._rng.random() > self.p:
            continue
        m.tree.learn(v, target)
        if m.background is not None:
            m.background.learn(v, target)
    return self

predict_one

predict_one(
    x: Any, t: float | None = None, return_std: bool = False
) -> Any

Mean of the trees, 0.0 before the first sample.

With return_std the result is a pair: the mean and the standard deviation of the predictions of the trees.

Source code in dense_armor/core/online/forest/oxt.py
def predict_one(
    self, x: Any, t: float | None = None, return_std: bool = False
) -> Any:
    """Mean of the trees, 0.0 before the first sample.

    With ``return_std`` the result is a pair: the mean and the standard
    deviation of the predictions of the trees.
    """
    v = self._vector(x) if self.members_ else None
    if v is None:
        return (0.0, 0.0) if return_std else 0.0
    preds = np.array([m.tree.predict(v) for m in self.members_])
    if return_std:
        return float(preds.mean()), float(preds.std())
    return float(preds.mean())

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.