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}))
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}))
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):
\(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.

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_)
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.

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
|
max_nodes
|
int | None
|
maximum number of nodes, or |
None
|
leaf
|
str
|
|
'nb'
|
criterion
|
str
|
|
'entropy'
|
splitter
|
str
|
the candidates of a numeric split: |
'class_means'
|
n_splits
|
int
|
number of thresholds of the |
10
|
nominal_attributes
|
Any
|
names of the categorical features, or |
None
|
max_active_leaves
|
int | None
|
number of leaves that keep statistics, or |
1000
|
memory_period
|
int
|
samples between two memory checks. Default 1000. |
1000
|
quantile_radius
|
float | None
|
slot width of the |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
on a bad |
Source code in dense_armor/core/online/tree/hoeffding.py
n_active_leaves_
property
¶
Number of leaves that keep statistics and try to split.
learn_one ¶
Update the tree with one sample.
Source code in dense_armor/core/online/tree/hoeffding.py
predict_proba_one ¶
Return the class-probability dict at the reached leaf.
Source code in dense_armor/core/online/tree/hoeffding.py
predict_one ¶
Return the most likely class.
explain_one ¶
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
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
|
max_nodes
|
int | None
|
maximum number of nodes, or |
None
|
splitter
|
str
|
|
'ebst'
|
nominal_attributes
|
Any
|
names of the categorical features, or |
None
|
max_active_leaves
|
int | None
|
leaves that keep statistics, or |
1000
|
memory_period
|
int
|
samples between two memory checks. Default 1000. |
1000
|
quantile_radius
|
float | None
|
slot width of the |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
on a bad |
Source code in dense_armor/core/online/tree/hoeffding_regressor.py
learn_one ¶
Update the tree with one sample.
Source code in dense_armor/core/online/tree/hoeffding_regressor.py
predict_one ¶
The mean of the target at the reached leaf (and its standard deviation).
Source code in dense_armor/core/online/tree/hoeffding_regressor.py
explain_one ¶
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
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):
NumericObserverkeeps a running Gaussian per class (it is adict{class: _Gauss}, so the naive-Bayes leaf reads it as before) and, bysplitter, 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.
NominalObserverkeeps 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
best_candidate ¶
(gain, threshold) of the best split of this feature, or (-1.0, None).
Source code in dense_armor/core/online/tree/splitters.py
test_gain ¶
Gain of the split x <= threshold on the data of this observer, or None.
Source code in dense_armor/core/online/tree/splitters.py
NominalObserver ¶
Bases: dict
{category: {class: count}} of one nominal feature at one leaf.
best_candidate ¶
(gain, category): the best "value == category" test, or (-1.0, None).
Source code in dense_armor/core/online/tree/splitters.py
cond_proba ¶
Laplace estimate of P(value | class), with one extra slot for a new category.
Source code in dense_armor/core/online/tree/splitters.py
TargetNumericObserver ¶
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
best_candidate ¶
TargetNominalObserver ¶
Bases: dict
{category: [n, sum, sum_sq]} of the target, for one nominal feature at one leaf.
best_candidate ¶
(variance reduction, category) of the best "value == category" test.
Source code in dense_armor/core/online/tree/splitters.py
merit_range ¶
Range of the merit of a split with k classes (for the Hoeffding bound).
split_gain ¶
Impurity of the parent minus the weighted impurity of the two sides, or None.
Source code in dense_armor/core/online/tree/splitters.py
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:
criterionis"entropy"(default) or"gini";splitteris"class_means"(default, the midpoints above),"gaussian"(n_splitsevenly 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 widthquantile_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 innominal_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 themax_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_depthandmax_nodesremain available.HoeffdingTreeRegressorsplits 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_sis about ten times the 99th percentile oflearn_onemeasured 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".