Skip to content

Hoeffding tree: a tree that waits for proof

A decision tree asks a chain of yes/no questions and ends with an answer. The Hoeffding tree (Domingos and Hulten 2000) learns that chain one sample at a time: a leaf becomes a question only when the data it has seen prove, with a stated probability, that the question is the best one. It never needs the whole table in memory, and it can be read: explain_one gives the path of questions behind each answer.

class predicts page section
HoeffdingTreeClassifier a class, with its probabilities 1 and 2
HoeffdingTreeRegressor a number 3

Trees that change their mind after a split are on the next pages: the Anytime tree and the Adaptive tree.

1. A tree that flags card payments

A bank wants to flag card payments that look like fraud. Three thousand payments arrive one at a time: most are small and made in the afternoon (an amount around 60, at about 14:00), a few are large and made at night (an amount around 400, at about 03:00). After each payment the tree is told whether it was fraud.

import numpy as np
from dense_armor.core.online.tree import HoeffdingTreeClassifier

rng = np.random.default_rng(0)
tree = HoeffdingTreeClassifier(grace_period=100)
for _ in range(3000):
    normal = rng.random() < 0.8
    amount = rng.normal(60, 20) if normal else rng.normal(400, 100)
    hour = rng.normal(14, 3) if normal else rng.normal(3, 2)
    tree.learn_one({"amount": amount, "hour": hour}, int(not normal))
print(tree.predict_one({"amount": 45.0, "hour": 15.0}), tree.predict_one({"amount": 420.0, "hour": 2.0}))
print(tree.explain_one({"amount": 420.0, "hour": 2.0}))
print(tree.n_nodes_, tree.predict_proba_one({"amount": 420.0, "hour": 2.0}))
0 1
[{'feature': 'amount', 'threshold': 232.60942718228952, 'side': 'right'}]
3 {0: 0.0, 1: 1.0}

The tree has 3 nodes: one question, is the amount above 232.61?, and two leaves. The threshold lies between the usual amounts and the suspicious ones, and the hour was not needed. predict_proba_one gives the probability of each class (here the tree is sure), and explain_one the path of questions behind an answer. When to split, and why the tree can be trusted to do so, is in the next section.

2. A tree that learns a robot state

Two states of an arm: idle (0) and carrying a load (1). The load raises the joint torque tau; the velocity qd says nothing about it.

import numpy as np
from dense_armor.core.online.tree import HoeffdingTreeClassifier

rng = np.random.default_rng(0)
ht = HoeffdingTreeClassifier(grace_period=100)
for _ in range(2000):
    y = int(rng.random() < 0.5)
    x = {"tau": rng.normal(2.0 + 3.0 * y, 0.5), "qd": rng.normal(0.0, 1.0)}
    ht.learn_one(x, y)
print(ht.predict_one({"tau": 1.8, "qd": 0.3}), ht.predict_one({"tau": 5.2, "qd": -0.4}))
print(ht.explain_one({"tau": 5.2, "qd": -0.4}))
0 1
[{'feature': 'tau', 'threshold': 3.5024219539142933, 'side': 'right'}]

The tree split on tau at 3.50, halfway between the two states (2.0 and 5.0), and ignored qd. explain_one gives the path of questions for one sample. When to split: every grace_period samples a leaf compares the two best splits; it splits when the gain of the best exceeds the second by more than the Hoeffding bound (Manapragada et al. 2018, eq. 1):

\[\epsilon = \sqrt{\frac{R^2 \ln(1/\delta)}{2n}}\]

\(R\) is the range of the gain (\(\log_2\) of the number of classes), \(n\) the samples at the leaf, \(\delta\) the probability of choosing the wrong split. With two classes (\(R = 1\)), \(\delta = 10^{-7}\) and \(n = 200\), \(\epsilon = 0.20\): the best split must win by 0.20 bits.

A Hoeffding tree on a robot arm: the question it learned (tau above 3.50), the Hoeffding bound that shrinks with the samples, and the accuracy over time with the first split.

Left: the 2000 samples of the first example, the two states of the arm and the one question the tree learned. Centre: the doubt it must overcome before asking it, the bound \(\epsilon\), which falls as the leaf sees more samples. Right: the accuracy of the last 100 predictions, tested before the tree learns each sample; the first split comes at sample 100, the first moment the tree is allowed to check (grace_period=100).

3. Predicting a number: HoeffdingTreeRegressor

The same idea for a number: a split is made when it lowers the variance of the target enough, by the same bound. It predicts the gravity torque of the first joint of a two-link arm from the two joint angles, tested before learning each sample.

import numpy as np
from dense_armor.core.evaluation.metrics import MeanAbsoluteError
from dense_armor.core.online.tree import HoeffdingTreeRegressor

rng = np.random.default_rng(3)
ht = HoeffdingTreeRegressor(grace_period=100)
mae, mae_mean, mean, n = MeanAbsoluteError(), MeanAbsoluteError(), 0.0, 0
for _ in range(20000):
    q1, q2 = rng.uniform(-np.pi, np.pi, 2)
    tau = 9.81 * (2.0 * np.cos(q1) + np.cos(q1 + q2))
    x = {"q1": q1, "q2": q2}
    mae.update(tau, ht.predict_one(x))
    mae_mean.update(tau, mean)
    ht.learn_one(x, tau)
    n += 1
    mean += (tau - mean) / n
print(round(mae.get(), 3), round(mae_mean.get(), 3), ht.n_nodes_, ht.n_active_leaves_)
5.159 13.241 73 37

The mean absolute error is 5.2 N·m against 13.2 N·m for the running mean, with 73 nodes, 37 of them leaves that still keep statistics. The stochastic gradient tree on the same problem reaches 7.7 N·m with 91 nodes.

A Hoeffding regression tree against the true gravity torque: the true surface, the tree after 20000 samples as steps, and the absolute error on a grid.

The figure shows what the tree learned: the torque (left) cut into flat steps (centre), more and finer where the surface bends. The error map (right) is measured on a regular grid of angles after the 20000 samples (mean 3.1 N·m); the 5.2 N·m above is the error of each prediction tested before learning, so it includes the early samples, when the tree was small.

API reference

hoeffding

Hoeffding tree classifier.

A non-linear classifier that grows one sample at a time. Each leaf keeps enough statistics to estimate the gain of a possible split; when the difference in gain between the best and the second-best candidate is larger than the Hoeffding bound, the leaf is split.

The Hoeffding bound of equation 1 of Manapragada et al. 2018 is

.. math::

\epsilon = \sqrt{\frac{R^2 \ln(1/\delta)}{2 n}}

where R is the range of the split-evaluation function (log2(K) for the entropy and 1 - 1/K for the Gini impurity, with K classes), delta is one minus the required confidence, and n is the number of samples seen at the leaf.

Split criterion. criterion="entropy" (information gain, the default) or "gini" (reduction of the Gini impurity).

Numeric features. A running Gaussian per class and per feature inside each leaf (also the naive-Bayes leaf). The candidates of a split come from splitter: "class_means" (default; the midpoints between the means of the classes), "gaussian" (n_splits thresholds between the smallest and the largest value, with the class shares from the normal CDF), "ebst" (every boundary between two consecutive distinct values, on exact counts) or "quantile" (the boundaries between the slots of a quantizer); see :mod:dense_armor.core.online.tree.splitters.

Categorical features. A feature is categorical when its name is in nominal_attributes, or when nominal_attributes is "auto" and its first value is a string that is not a number (without either, a value that is not a number makes the sample count as missing, as before). A categorical feature is split as "the value is this category" against all the others; the leaf classifier uses a Laplace-smoothed P(category | class).

Memory. max_active_leaves (default 1000) bounds the statistics of the tree: every memory_period samples the leaves are ranked by the errors they have made (the promise of a leaf, p_l * e_l, of Domingos and Hulten 2000, since p_l * e_l is the share of the stream's errors made at the leaf) and only the most promising ones keep their statistics and go on trying to split. A deactivated leaf keeps counting the classes, so it still predicts the majority class, and it is reactivated, with new statistics, when it becomes one of the most promising. The tree itself is not capped (max_nodes defaults to None) and can grow to any depth. max_nodes and max_depth remain as hard limits when a user wants them.

Examples:

>>> import numpy as np
>>> from dense_armor.core.online.tree.hoeffding import HoeffdingTreeClassifier
>>> rng = np.random.default_rng(0)
>>> h = HoeffdingTreeClassifier(grace_period=30)
>>> 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

A categorical feature, with the Gini criterion:

>>> h = HoeffdingTreeClassifier(
...     grace_period=30, criterion="gini", nominal_attributes=["colour"]
... )
>>> for _ in range(400):
...     colour = "red" if rng.random() < 0.5 else "blue"
...     _ = h.learn_one({"colour": colour}, y=colour == "red")
>>> h.predict_one({"colour": "red"}), h.predict_one({"colour": "blue"})
(True, False)
References

Manapragada, C., Webb, G. I., Salehi, M. (2018). Extremely fast decision tree. In KDD. Domingos, P., Hulten, G. (2000). Mining high-speed data streams. In KDD.

HoeffdingTreeClassifier

HoeffdingTreeClassifier(
    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",
    dtype: Any = 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: Classifier

Hoeffding tree for incremental classification.

Memory is bounded by max_active_leaves: only that many leaves keep statistics, so memory_class is "O(window)" in the statistics (the nodes themselves are small, and max_nodes can cap them).

budget_s = 1e-3 s: p99 of learn_one measured at 2.3e-5 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 number of 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 (default).

None
max_nodes int | None

maximum number of nodes, or None (default).

None
leaf str

"nb" or "majority". With "nb", a leaf in which any class has fewer than two samples answers like "majority", because the Gaussian likelihood of that class cannot be estimated.

'nb'
criterion str

"entropy" (information gain, default) or "gini".

'entropy'
splitter str

the candidates of a numeric split: "class_means" (default), "gaussian", "ebst" or "quantile".

'class_means'
n_splits int

number of thresholds of the "gaussian" splitter. Default 10.

10
nominal_attributes Any

names of the categorical features, or "auto" to take as categorical every feature whose first value is a non-numeric string. Default None: all the features are numeric.

None
max_active_leaves int | None

number of leaves that keep statistics, or None for no limit. Default 1000.

1000
memory_period int

samples between two memory checks. Default 1000.

1000
quantile_radius float | None

slot width of the "quantile" splitter, or None for a third of the standard deviation of the first 30 values.

None

Raises:

Type Description
ValueError

on a bad leaf, criterion or splitter, or a non-positive parameter.

Source code in dense_armor/core/online/tree/hoeffding.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",
    dtype: Any = 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,
) -> None:
    if grace_period < 1:
        raise ValueError(f"grace_period must be >= 1, got {grace_period}")
    if not 0.0 < delta < 1.0:
        raise ValueError(f"delta must be in (0, 1), got {delta}")
    if tau < 0.0:
        raise ValueError(f"tau must be >= 0, got {tau}")
    if max_depth is not None and max_depth < 1:
        raise ValueError(f"max_depth must be >= 1, got {max_depth}")
    if max_nodes is not None and max_nodes < 1:
        raise ValueError(f"max_nodes must be >= 1, got {max_nodes}")
    if leaf not in ("nb", "majority"):
        raise ValueError(f"leaf must be 'nb' or 'majority', got {leaf!r}")
    if criterion not in CRITERIA:
        raise ValueError(f"criterion must be one of {CRITERIA}, got {criterion!r}")
    if splitter not in SPLITTERS:
        raise ValueError(f"splitter must be one of {SPLITTERS}, got {splitter!r}")
    if n_splits < 1:
        raise ValueError(f"n_splits must be >= 1, got {n_splits}")
    if max_active_leaves is not None and max_active_leaves < 1:
        raise ValueError(f"max_active_leaves must be >= 1, got {max_active_leaves}")
    if memory_period < 1:
        raise ValueError(f"memory_period must be >= 1, got {memory_period}")
    if quantile_radius is not None and quantile_radius <= 0.0:
        raise ValueError(f"quantile_radius must be > 0, got {quantile_radius}")
    self.grace_period = grace_period
    self.delta = delta
    self.tau = tau
    self.max_depth = max_depth
    self.max_nodes = max_nodes
    self.leaf = leaf
    self.dtype = dtype
    self.criterion = criterion
    self.splitter = splitter
    self.n_splits = n_splits
    self.nominal_attributes = nominal_attributes
    self.max_active_leaves = max_active_leaves
    self.memory_period = memory_period
    self.quantile_radius = quantile_radius
    if isinstance(nominal_attributes, str) and nominal_attributes != "auto":
        raise ValueError(
            f"nominal_attributes must be a list of names or 'auto', got {nominal_attributes!r}"
        )
    self._auto_nominal = nominal_attributes == "auto"
    self._nominal_set = (
        frozenset()
        if isinstance(nominal_attributes, str)
        else frozenset(nominal_attributes or ())
    )
    self._kinds_: dict = {}
    self.root_: _Node | None = None
    self.n_nodes_ = 0
    self.classes_: set = set()
    self.features_: set = set()
    self.n_seen_ = 0
    self.n_missing_ = 0

n_active_leaves_ property

n_active_leaves_: int

Number of leaves that keep statistics and try to split.

learn_one

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

Update the tree with one sample.

Source code in dense_armor/core/online/tree/hoeffding.py
def learn_one(
    self, x: Any, y: Any, t: float | None = None
) -> "HoeffdingTreeClassifier":
    """Update the tree with one sample."""
    self._time_step(t)
    d = self._validate(x, y)
    if d is None:
        return self
    self.classes_.add(y)
    if self.root_ is None:
        self.root_ = self._new_leaf(0)
    path = self._path(d)
    leaf = path[-1]
    self._update_leaf(leaf, d, y)
    self.n_seen_ += 1
    if leaf.is_leaf and leaf.n_ % self.grace_period == 0:
        self._try_split(leaf)
    self._tick_memory()
    return self

predict_proba_one

predict_proba_one(x: Any, t: float | None = None) -> dict

Return the class-probability dict at the reached leaf.

Source code in dense_armor/core/online/tree/hoeffding.py
def predict_proba_one(self, x: Any, t: float | None = None) -> dict:
    """Return the class-probability dict at the reached leaf."""
    if self.root_ is None:
        return {}
    d = _as_dict(x)
    path = self._path(d)
    return self._predict_proba_leaf(path[-1], d)

predict_one

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

Return the most likely class.

Source code in dense_armor/core/online/tree/hoeffding.py
def predict_one(self, x: Any, t: float | None = None) -> Any:
    """Return the most likely class."""
    if self.root_ is None:
        return None
    d = _as_dict(x)
    path = self._path(d)
    return self._predict_class_leaf(path[-1], d)

explain_one

explain_one(x: Any, t: float | None = None) -> list

Return the path from root to leaf as a list of dicts.

A numeric split gives {"feature", "threshold", "side"} and a categorical one {"feature", "category", "side"}.

Returns an empty list when the root itself is a leaf, that is when the tree never split from the root. This happens on small datasets where the Hoeffding bound (or the t-test for SGT) is never satisfied, so no split is statistically significant. The prediction is then a constant prior over the classes and there is no path to explain.

Source code in dense_armor/core/online/tree/hoeffding.py
def explain_one(self, x: Any, t: float | None = None) -> list:
    """Return the path from root to leaf as a list of dicts.

    A numeric split gives ``{"feature", "threshold", "side"}`` and a
    categorical one ``{"feature", "category", "side"}``.

    Returns an empty list when the root itself is a leaf, that is
    when the tree never split from the root. This happens on
    small datasets where the Hoeffding bound (or the t-test for
    SGT) is never satisfied, so no split is statistically
    significant. The prediction is then a constant prior over the
    classes and there is no path to explain.
    """
    if self.root_ is None:
        return []
    d = _as_dict(x)
    cur: _Node | None = self.root_
    out: list = []
    while cur is not None and not cur.is_leaf:
        f = cur.split_feature_
        v = d.get(f)
        if v is None:
            break
        try:
            left = self._goes_left(cur, v)
        except (TypeError, ValueError):
            break
        side = "left" if left else "right"
        if cur.split_category_ is not None:
            out.append(
                {"feature": f, "category": cur.split_category_, "side": side}
            )
        else:
            out.append(
                {"feature": f, "threshold": cur.split_threshold_, "side": side}
            )
        cur = cur.left_ if left else cur.right_
    return out

hoeffding_regressor

Hoeffding tree regressor, with the variance reduction as the split criterion.

The regression counterpart of :class:HoeffdingTreeClassifier. A leaf keeps the count, the sum and the sum of squares of the target, and for every feature an observer that can tell the best split of that feature. The merit of a split is the reduction of the variance of the target,

.. math::

VR = \mathrm{Var}(S) - \frac{n_L}{n}\mathrm{Var}(S_L) - \frac{n_R}{n}\mathrm{Var}(S_R).

The merit used in the test is the relative reduction, VR / Var(S), which lies in [0, 1] whatever the scale of the target, so the range of the merit in the Hoeffding bound is 1. The tree splits a leaf when the best merit exceeds the larger of the second-best merit and 0 (the merit of not splitting) by more than epsilon, or when epsilon < tau (a tie); so a leaf whose best split reduces the variance by no more than noise does is not split. The leaf predicts the mean of its target.

Numeric features. splitter="ebst" (default) keeps the distinct values with their target sums and evaluates every boundary between them (the E-BST of the paper above), at most 256 per feature and leaf: above that, neighbouring values are merged and the search is an approximation; splitter="quantile" quantizes the values into slots of a fixed width and evaluates the boundaries between occupied slots (the quantizer of Mastelini and de Carvalho 2021), with at most 256 slots per feature and leaf. Categorical features are those named in nominal_attributes (or all the features whose first value is a non-numeric string, with "auto"); the split is "the value is this category" against the rest.

Memory. As in the classifier: max_active_leaves (default 1000) keeps the statistics of the leaves that have made the largest total absolute error, and the other leaves keep only the mean of the target. The tree has no node cap by default.

Examples:

>>> import numpy as np
>>> from dense_armor.core.online.tree.hoeffding_regressor import HoeffdingTreeRegressor
>>> rng = np.random.default_rng(0)
>>> t = HoeffdingTreeRegressor(grace_period=50)
>>> for _ in range(1500):
...     x = float(rng.random())
...     _ = t.learn_one({"x": x}, (5.0 if x > 0.5 else 1.0) + float(rng.normal(0, 0.1)))
>>> round(t.predict_one({"x": 0.9})), round(t.predict_one({"x": 0.1}))
(5, 1)
References

Ikonomovska, E., Gama, J., Dzeroski, S. (2011). Learning model trees from evolving data streams. Data Mining and Knowledge Discovery 23(1). Mastelini, S. M., de Carvalho, A. C. P. L. F. (2021). Using dynamical quantization to perform split attempts in online tree regressors. Pattern Recognition Letters 145.

HoeffdingTreeRegressor

HoeffdingTreeRegressor(
    grace_period: int = 200,
    delta: float = 1e-07,
    tau: float = 0.05,
    max_depth: int | None = None,
    max_nodes: int | None = None,
    splitter: str = "ebst",
    nominal_attributes: Any = None,
    max_active_leaves: int | None = 1000,
    memory_period: int = 1000,
    quantile_radius: float | None = None,
)

Bases: Regressor

Hoeffding tree for incremental regression, split by the variance reduction.

Parameters:

Name Type Description Default
grace_period int

samples at a leaf between two split attempts.

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 (default).

None
max_nodes int | None

maximum number of nodes, or None (default).

None
splitter str

"ebst" (default) or "quantile".

'ebst'
nominal_attributes Any

names of the categorical features, or "auto", or None (all numeric).

None
max_active_leaves int | None

leaves that keep statistics, or None for no limit. Default 1000.

1000
memory_period int

samples between two memory checks. Default 1000.

1000
quantile_radius float | None

slot width of the "quantile" splitter, or None for a third of the standard deviation of the first 30 values.

None

Raises:

Type Description
ValueError

on a bad splitter or a non-positive parameter.

Source code in dense_armor/core/online/tree/hoeffding_regressor.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,
    splitter: str = "ebst",
    nominal_attributes: Any = None,
    max_active_leaves: int | None = 1000,
    memory_period: int = 1000,
    quantile_radius: float | None = None,
) -> None:
    if grace_period < 1:
        raise ValueError(f"grace_period must be >= 1, got {grace_period}")
    if not 0.0 < delta < 1.0:
        raise ValueError(f"delta must be in (0, 1), got {delta}")
    if tau < 0.0:
        raise ValueError(f"tau must be >= 0, got {tau}")
    if max_depth is not None and max_depth < 1:
        raise ValueError(f"max_depth must be >= 1, got {max_depth}")
    if max_nodes is not None and max_nodes < 1:
        raise ValueError(f"max_nodes must be >= 1, got {max_nodes}")
    if splitter not in TARGET_SPLITTERS:
        raise ValueError(
            f"splitter must be one of {TARGET_SPLITTERS}, got {splitter!r}"
        )
    if max_active_leaves is not None and max_active_leaves < 1:
        raise ValueError(f"max_active_leaves must be >= 1, got {max_active_leaves}")
    if memory_period < 1:
        raise ValueError(f"memory_period must be >= 1, got {memory_period}")
    if quantile_radius is not None and quantile_radius <= 0.0:
        raise ValueError(f"quantile_radius must be > 0, got {quantile_radius}")
    if isinstance(nominal_attributes, str) and nominal_attributes != "auto":
        raise ValueError(
            f"nominal_attributes must be a list of names or 'auto', got {nominal_attributes!r}"
        )
    self.grace_period = grace_period
    self.delta = delta
    self.tau = tau
    self.max_depth = max_depth
    self.max_nodes = max_nodes
    self.splitter = splitter
    self.nominal_attributes = nominal_attributes
    self.max_active_leaves = max_active_leaves
    self.memory_period = memory_period
    self.quantile_radius = quantile_radius
    self._auto_nominal = nominal_attributes == "auto"
    self._nominal_set = (
        frozenset()
        if isinstance(nominal_attributes, str)
        else frozenset(nominal_attributes or ())
    )
    self._kinds_: dict = {}
    self.root_: _RNode | None = None
    self.n_nodes_ = 0
    self.n_seen_ = 0
    self.n_missing_ = 0

learn_one

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

Update the tree with one sample.

Source code in dense_armor/core/online/tree/hoeffding_regressor.py
def learn_one(
    self, x: dict, y: Any, t: float | None = None
) -> "HoeffdingTreeRegressor":
    """Update the tree with one sample."""
    self._time_step(t)
    checked = self._validate(x, y)
    if checked is None:
        return self
    d, fy = checked
    if self.root_ is None:
        self.root_ = self._new_leaf(0)
    leaf = self._path(d)[-1]
    self._update_leaf(leaf, d, fy)
    self.n_seen_ += 1
    if leaf.is_leaf and leaf.n_ % self.grace_period == 0:
        self._try_split(leaf)
    if (
        self.max_active_leaves is not None
        and self.n_seen_ % self.memory_period == 0
    ):
        self._enforce_memory()
    return self

predict_one

predict_one(
    x: dict,
    t: float | None = None,
    return_std: bool = False,
)

The mean of the target at the reached leaf (and its standard deviation).

Source code in dense_armor/core/online/tree/hoeffding_regressor.py
def predict_one(self, x: dict, t: float | None = None, return_std: bool = False):
    """The mean of the target at the reached leaf (and its standard deviation)."""
    if self.root_ is None:
        return (0.0, 0.0) if return_std else 0.0
    leaf = self._path(_as_dict(x))[-1]
    mean = leaf.mean
    if not return_std:
        return mean
    if leaf.n_ < 2:
        return mean, 0.0
    var = max(0.0, leaf.sum_sq_ / leaf.n_ - mean * mean)
    return mean, math.sqrt(var)

explain_one

explain_one(x: dict, t: float | None = None) -> list

The path from the root to the leaf of x, as a list of dicts.

Source code in dense_armor/core/online/tree/hoeffding_regressor.py
def explain_one(self, x: dict, t: float | None = None) -> list:
    """The path from the root to the leaf of ``x``, as a list of dicts."""
    if self.root_ is None:
        return []
    d = _as_dict(x)
    cur: _RNode | None = self.root_
    out: list = []
    while cur is not None and not cur.is_leaf:
        f = cur.split_feature_
        v = d.get(f)
        if v is None:
            break
        try:
            left = self._goes_left(cur, v)
        except (TypeError, ValueError):
            break
        side = "left" if left else "right"
        if cur.split_category_ is not None:
            out.append(
                {"feature": f, "category": cur.split_category_, "side": side}
            )
        else:
            out.append(
                {"feature": f, "threshold": cur.split_threshold_, "side": side}
            )
        cur = cur.left_ if left else cur.right_
    return out

splitters

Attribute observers, split criteria and split candidates of the Hoeffding trees.

An observer sees the values of one feature at one leaf, together with the class (or the target), and answers one question: what is the best split of this feature, and how good is it? The trees ask it when a leaf has seen grace_period more samples.

Classification (HoeffdingTreeClassifier and the trees built on it):

  • NumericObserver keeps a running Gaussian per class (it is a dict {class: _Gauss}, so the naive-Bayes leaf reads it as before) and, by splitter, the candidates of one of four methods:

"class_means" (default, the historical one) the midpoints between the means of the classes; the share of each class on each side is read from the normal CDF. "gaussian" n_splits thresholds evenly spaced between the smallest and the largest value seen, with the class shares from the normal CDF, as the Gaussian numeric observer of MOA and of River. "ebst" the exhaustive search: the distinct values seen are kept, with their class counts, and every boundary between two consecutive values is a candidate (the extended binary search tree of Ikonomovska, Gama and Dzeroski 2011, here with class counts instead of target sums). At most max_values values are kept (256): when there are more, the two neighbouring values with the fewest samples are merged and the larger one is kept. Below the limit the search is exact; above it, it is an approximation. The limit is a choice of this library, not of the paper. "quantile" a quantization observer: the values fall in slots of a fixed width, a slot keeps its mean and its class counts, and the boundaries between occupied slots are the candidates. The width is a third of the standard deviation of the first 30 values, or quantile_radius (the quantizer of Mastelini and de Carvalho 2021, with the class counts of the classification case). At most max_values slots are kept (256): when there are more, the two neighbouring slots with the fewest samples are merged. The limit is a choice of this library.

  • NominalObserver keeps the class counts of every category; a candidate is "the value is this category" against all the others.

The criteria are the information gain on the entropy ("entropy") and on the Gini impurity ("gini"). The range of the merit, used by the Hoeffding bound, is log2(K) for the entropy and 1 - 1/K for the Gini impurity, with K the number of classes.

Regression (HoeffdingTreeRegressor): TargetNumericObserver and TargetNominalObserver keep the count, the sum and the sum of squares of the target, and the criterion is the reduction of the variance.

NumericObserver

NumericObserver(
    splitter="class_means",
    dtype=None,
    n_splits=10,
    radius=None,
    max_values=MAX_VALUES,
)

Bases: dict

{class: _Gauss} of one numeric feature at one leaf, and the state of its splitter.

Source code in dense_armor/core/online/tree/splitters.py
def __init__(
    self,
    splitter="class_means",
    dtype=None,
    n_splits=10,
    radius=None,
    max_values=MAX_VALUES,
):
    super().__init__()
    self.max_values = max_values
    self.splitter = splitter
    self.dtype = dtype
    self.n_splits = n_splits
    self.lo = math.inf
    self.hi = -math.inf
    self._vals: list = []
    self._cnts: list = []
    self._sizes: list = []
    self._radius = radius
    self._slots: dict = {}
    self._keys: list = []
    self._warm: list = []

best_candidate

best_candidate(
    criterion: str, class_counts: dict, n: float
)

(gain, threshold) of the best split of this feature, or (-1.0, None).

Source code in dense_armor/core/online/tree/splitters.py
def best_candidate(self, criterion: str, class_counts: dict, n: float):
    """``(gain, threshold)`` of the best split of this feature, or ``(-1.0, None)``."""
    if self.splitter in ("ebst", "quantile"):
        return _scan(criterion, self._points())
    best_gain, best_thr = -1.0, None
    for s in self._thresholds():
        left, right = self._cdf_counts(s, class_counts)
        g = split_gain(criterion, class_counts, n, left, right)
        if g is not None and g > best_gain:
            best_gain, best_thr = g, s
    return best_gain, best_thr

test_gain

test_gain(
    criterion: str,
    class_counts: dict,
    n: float,
    threshold: float,
)

Gain of the split x <= threshold on the data of this observer, or None.

Source code in dense_armor/core/online/tree/splitters.py
def test_gain(self, criterion: str, class_counts: dict, n: float, threshold: float):
    """Gain of the split ``x <= threshold`` on the data of this observer, or ``None``."""
    if self.splitter in ("ebst", "quantile"):
        return _exact_gain(criterion, self._points(), threshold)
    left, right = self._cdf_counts(threshold, class_counts)
    return split_gain(criterion, class_counts, n, left, right)

NominalObserver

Bases: dict

{category: {class: count}} of one nominal feature at one leaf.

best_candidate

best_candidate(
    criterion: str, class_counts: dict, n: float
)

(gain, category): the best "value == category" test, or (-1.0, None).

Source code in dense_armor/core/online/tree/splitters.py
def best_candidate(self, criterion: str, class_counts: dict, n: float):
    """``(gain, category)``: the best "value == category" test, or ``(-1.0, None)``."""
    if len(self) < 2:
        return -1.0, None
    pts = self._points()
    total = _totals(pts)
    n_obs = float(sum(total.values()))
    best_gain, best_cat = -1.0, None
    for cat, counts in pts:
        right = {
            k: total[k] - counts.get(k, 0)
            for k in total
            if total[k] - counts.get(k, 0) > 0
        }
        g = split_gain(criterion, total, n_obs, dict(counts), right)
        if g is not None and g > best_gain:
            best_gain, best_cat = g, cat
    return best_gain, best_cat

cond_proba

cond_proba(value, cls, class_n: float) -> float

Laplace estimate of P(value | class), with one extra slot for a new category.

Source code in dense_armor/core/online/tree/splitters.py
def cond_proba(self, value, cls, class_n: float) -> float:
    """Laplace estimate of ``P(value | class)``, with one extra slot for a new category."""
    seen = self.get(value)
    n_vc = seen.get(cls, 0) if seen else 0
    return (n_vc + 1.0) / (class_n + len(self) + 1.0)

TargetNumericObserver

TargetNumericObserver(
    splitter="ebst", radius=None, max_values=MAX_VALUES
)

Target statistics of one numeric feature at one leaf, for the variance reduction.

splitter is "ebst" (the distinct values, exhaustive, the E-BST of Ikonomovska et al. 2011) or "quantile" (slots of a fixed width, the quantizer of Mastelini and de Carvalho 2021). Both keep at most max_values values or slots (256): when there are more, the two neighbouring ones with the fewest samples are merged into the upper one.

Source code in dense_armor/core/online/tree/splitters.py
def __init__(self, splitter="ebst", radius=None, max_values=MAX_VALUES):
    self.splitter = splitter
    self.max_values = max_values
    self._vals: list = []
    self._stats: list = []
    self._sizes: list = []
    self._radius = radius
    self._slots: dict = {}
    self._keys: list = []
    self._warm: list = []

best_candidate

best_candidate()

(variance reduction, threshold) of the best split, or (-1.0, None).

Source code in dense_armor/core/online/tree/splitters.py
def best_candidate(self):
    """``(variance reduction, threshold)`` of the best split, or ``(-1.0, None)``."""
    return _target_scan(self._points())

TargetNominalObserver

Bases: dict

{category: [n, sum, sum_sq]} of the target, for one nominal feature at one leaf.

best_candidate

best_candidate()

(variance reduction, category) of the best "value == category" test.

Source code in dense_armor/core/online/tree/splitters.py
def best_candidate(self):
    """``(variance reduction, category)`` of the best "value == category" test."""
    if len(self) < 2:
        return -1.0, None
    n = sum(st[0] for st in self.values())
    s = sum(st[1] for st in self.values())
    s2 = sum(st[2] for st in self.values())
    parent = _variance(n, s, s2)
    best_gain, best_cat = -1.0, None
    for cat, (cn, cs, cs2) in self.items():
        rn = n - cn
        if cn <= 0 or rn <= 0:
            continue
        gain = (
            parent
            - (cn / n) * _variance(cn, cs, cs2)
            - (rn / n) * _variance(rn, s - cs, s2 - cs2)
        )
        if gain > best_gain:
            best_gain, best_cat = gain, cat
    return best_gain, best_cat

merit_range

merit_range(criterion: str, k: int) -> float

Range of the merit of a split with k classes (for the Hoeffding bound).

Source code in dense_armor/core/online/tree/splitters.py
def merit_range(criterion: str, k: int) -> float:
    """Range of the merit of a split with ``k`` classes (for the Hoeffding bound)."""
    return math.log2(k) if criterion == "entropy" else 1.0 - 1.0 / k

split_gain

split_gain(
    criterion: str,
    parent: dict,
    n: float,
    left: dict,
    right: dict,
)

Impurity of the parent minus the weighted impurity of the two sides, or None.

Source code in dense_armor/core/online/tree/splitters.py
def split_gain(criterion: str, parent: dict, n: float, left: dict, right: dict):
    """Impurity of the parent minus the weighted impurity of the two sides, or ``None``."""
    n_l = sum(left.values())
    n_r = sum(right.values())
    if n_l <= 0.0 or n_r <= 0.0:
        return None
    return (
        impurity(criterion, parent)
        - (n_l / n) * impurity(criterion, left)
        - (n_r / n) * impurity(criterion, right)
    )

Details

  • Hoeffding tree: each leaf keeps a Gaussian per class and feature; candidate thresholds are midpoints between consecutive class means; leaves predict with naive Bayes (leaf="nb") or the majority class; tau (0.05) is the tie threshold. Domingos and Hulten (2000) introduced the tree; the bound and the Anytime variant are from Manapragada et al. (2018), Algorithm 3.1, Functions 3.2 and 3.3.
  • Hoeffding tree options: criterion is "entropy" (default) or "gini"; splitter is "class_means" (default, the midpoints above), "gaussian" (n_splits evenly spaced thresholds, the Gaussian CDF of each class on both sides), "ebst" (the distinct values are kept and every boundary between them is evaluated, Ikonomovska et al. 2011; at most 256 per feature and leaf, then the two neighbouring values with the fewest samples are merged, so above 256 the search is an approximation, a limit chosen here and not in the paper) or "quantile" (values quantized into slots of width quantile_radius, a third of the standard deviation of the first 30 values by default, Mastelini and de Carvalho 2021; at most 256 slots, merged in the same way). Features named in nominal_attributes (or all non-numeric strings with "auto") are categorical: the split is "equals this category" against the rest and the naive Bayes leaf uses Laplace-smoothed frequencies.
  • The tree has no node or depth limit by default: it grows to whatever depth the data justify. To keep the memory bounded the leaves with the least promise are deactivated: every memory_period (1000) samples only the max_active_leaves (1000) leaves that made the most errors keep their statistics, the others keep counting the classes and predict the majority but no longer split (Domingos and Hulten 2000, section 3.2). max_depth and max_nodes remain available. HoeffdingTreeRegressor splits on the variance reduction with the same observers ("ebst" default, "quantile"), and the same options for categories and memory.
  • The classes of this page bound their size with max_active_leaves; budget_s is about ten times the 99th percentile of learn_one measured on a desktop CPU.
  • Sources: Domingos, P., Hulten, G. (2000), "Mining high-speed data streams", KDD. Manapragada, C., Webb, G. I., Salehi, M. (2018), "Extremely fast decision tree", arXiv:1802.08780. Ikonomovska, E., Gama, J., Dzeroski, S. (2011), "Learning model trees from evolving data streams". Mastelini, S. M., de Carvalho, A. C. P. L. F. (2021), "Using dynamical quantization to perform split attempts in online tree regressors".