Skip to content

AggregatedMondrianForest: average every depth

A first example: the risk of a loan from a credit score

A bank rates each applicant with a credit score between 0 and 1. Below 0.4 the risk index of the loan is 0.8, above it 0.3, and every observed index carries a noise of 0.15. The forest sees 500 applicants, one at a time, and is then asked the index for six scores. The first line is the answer of the forest, the weighted average of every depth of its trees; the second is what the deepest leaf alone says.

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

rng = np.random.default_rng(0)
f = AggregatedMondrianForestRegressor(n_trees=10, seed=0)
for _ in range(500):
    score = float(rng.random())
    risk = 0.8 if score < 0.4 else 0.3
    f.learn_one({"score": score}, risk + float(rng.normal(0, 0.15)))
scores = (0.1, 0.2, 0.39, 0.41, 0.6, 0.9)
print([round(f.predict_one({"score": s}), 2) for s in scores])
print([round(f.predict_unaggregated_one({"score": s}), 2) for s in scores])
[0.68, 0.66, 0.51, 0.45, 0.4, 0.35]
[0.08, 0.36, 0.31, 0.2, 0.18, 0.07]

The true indices are 0.8 for the first three scores and 0.3 for the last three. The answer of the forest is smooth: it is high for low scores and low for high ones, and it spreads the step over the neighbourhood of 0.4 instead of cutting it. The leaf alone follows the noise of the few applicants it has seen and is far from the true values.

How it works

A tree has to decide how deep to go. A deep tree follows the data closely but memorises noise; a shallow one is steady but misses detail. AggregatedMondrianForestClassifier and AggregatedMondrianForestRegressor follow Mourtada, Gaiffas and Scornet and skip the decision: the answer is the average of the predictions of every pruning of the tree, each pruning weighted by how well it has predicted up to now. A pruning that has been predicting well counts more; a poor one fades.

There are exponentially many prunings, so the average sounds impossible. The paper shows that with a simple prior, a pruning with n nodes starting at weight 2^-n, the whole sum can be kept as two numbers per node and read along a single path from the leaf to the root. The library implements exactly that, so a prediction costs one walk up the tree.

The library already has a Mondrian forest. It smooths each tree with a fixed prior over where a path leaves the tree, so a node weighs the same whatever it has predicted. The aggregated forest replaces that fixed prior with weights learned from the loss of every node.

from dense_armor.core.online.forest import AggregatedMondrianForestRegressor

f = AggregatedMondrianForestRegressor(n_trees=10, seed=0)
for i in range(200):
    x = (i % 20) / 19.0
    f.learn_one({"x": x}, 1.0 if x > 0.5 else -1.0)
print(round(f.predict_one({"x": 0.9}), 2), round(f.predict_one({"x": 0.1}), 2))
0.99 -0.96

The target is -1 on the left half and +1 on the right half; the forest answers 0.99 and -0.96 at x = 0.9 and x = 0.1.

What the weighting does

The next figure uses a noisy curve. The red line is what the leaf alone predicts, which is the prediction of the deepest tree. The blue line is the weighted average of all prunings.

A noisy curve, the leaf prediction and the aggregated prediction

The leaf follows every wiggle of the noise. The aggregated line is smooth and follows the curve, at the cost of flattening the peaks: the average also includes shallow prunings, which predict the middle of a broad region. With a larger step the weights lean harder on the best pruning, and predict_unaggregated_one returns the leaf prediction for comparison.

What the paper guarantees

The paper bounds how much worse the aggregate can be than any single pruning. For the quadratic loss and targets in [-B, B], with step = 1 / (8 B^2), the loss of the forest exceeds that of any pruning T by at most 4 B^2 (|T| + 1) log n; for classification with the logarithmic loss and step = 1, by at most |T| log 2 + (|T| + 1)(K - 1)/4 * log(4n). Against the smallest pruning, the root alone, the bound is just log 2 / step.

Loss of the forest minus loss of the root alone, on two kinds of targets

On the left the targets are independent of x, so the root is the best answer, and the forest stays within a fraction of a unit of it, far below the bound of 5.5. On the right the targets follow a curve of x, the aggregate beats the root by more and more, and after 600 samples the difference is between -180 and -225. The bound only limits the damage; it says nothing about how much better the forest can be.

The parameters

Parameter Meaning Classifier Regressor
n_trees number of trees 10 10
step learning rate eta of the exponential weights 1.0 0.125
dirichlet symmetric Dirichlet parameter of the forecaster of a node (classifier only) 0.5
low, high the two ends of every feature 0.0, 1.0 0.0, 1.0
classes the label set, when known (classifier only); None grows it with the stream None
seed seed of the partitions None None
feature_keys names of the features; None takes the sorted keys of the first sample None None
max_nodes largest number of nodes of one tree; None lifts the limit 10000 10000

API reference

amf

Aggregated Mondrian forests (AMF) for classification and regression.

Page numbers below are PDF page indices of the paper's PDF, not the printed page numbers of the journal.

A Mondrian tree cuts the input box into cells; a forecaster in every cell predicts from the samples that fell in it. A deep tree fits well and a shallow one is stable, and which one is right is not known in advance. AMF does not choose: it answers with the average of the predictions of every pruning of the tree, each pruning weighted by how well it has predicted so far, following Mourtada, Gaiffas and Scornet.

For a tree with cell forecasters y_v, the prediction at x is the exponentially weighted average over all finite subtrees T

f_t(x) = sum_T pi(T) exp(-step L_{t-1}(T)) y_T(x)
         / sum_T pi(T) exp(-step L_{t-1}(T)),         (6, page 5)

with the prior pi(T) = 2^{-|T|} for |T| nodes (7, page 5) and L_{t-1}(T) the cumulative loss of the pruning T. There are exponentially many prunings; the prior makes the sum collapse to one weight pair per node, updated along one root-to-leaf path (Algorithm 2, page 9) and read along one path (Algorithm 3, page 11):

w_v    = exp(-step L_v)
wbar_v = w_v                            at a leaf
wbar_v = (w_v + wbar_v0 wbar_v1) / 2    at an inner node
y~_v   = (w_v / (2 wbar_v)) y_v + (wbar_v0 wbar_v1 / (2 wbar_v)) y~_va

where va is the child that contains x and y~ at the leaf is the forecaster of the leaf. The weights are kept as logarithms.

Relation to the Mondrian forest of the library. The Mondrian forest smooths the prediction of a tree with a fixed hierarchical prior over where a path leaves the tree, so a node weighs the same whatever the tree has predicted. AMF replaces that fixed prior with weights learned from the loss of every node, so a cell that has predicted badly is discounted, at a cost of two weights per node and no lifetime parameter.

What is implemented, and what is not. This is the version of Section 2 of the paper, on an unrestricted Mondrian partition of a box (Algorithm 2, page 9): the first sample in a cell is kept, and a second sample splits the cell until the two are separated. The version of Section 4 (restricted partition, splits above existing nodes, Algorithms 4 to 6, pages 17-19), which the paper uses in its experiments and for which it states no guarantee, is not implemented. The regret bounds below are those of the implemented version.

Regret, as the paper states it (page 13). With step = 1 and the logarithmic loss, for every finite subtree T of the partition and every sequence of samples (Corollary 1, equation 10),

sum_t loss(f_t(x_t), y_t) - sum_t loss(g_T(x_t), y_t)
    <= |T| log 2 + (|T| + 1) (K - 1) / 4 * log(4 n)

for any g_T constant on the leaves of T, with K classes and n samples. With the quadratic loss, targets in [-B, B] and step = 1 / (8 B^2) (Corollary 2, equation 11),

sum_t loss(f_t(x_t), y_t) - sum_t loss(g_T(x_t), y_t)
    <= 4 B^2 (|T| + 1) log n.

Both come from the exponential-weights bound of Lemma 1 (equation 9), (1 / step) |T| log 2 against the forecasters of the nodes. Nothing is claimed here beyond this: the bounds are for one tree, on a fixed partition, with the prediction made after the partition has been updated with x_t; the forest prediction is the mean of the tree predictions (equation 1) and, for a convex loss, inherits them.

Choices the paper does not fix, stated as my choice:

  • step and dirichlet are the names of this class. step is the learning rate eta of the paper (page 6). dirichlet is the parameter a of the symmetric Dirichlet prior of the forecaster of a node, (n_y + a) / (n + K a); a = 1/2 is the Krichevsky-Trofimov forecaster of equation 5 (page 5), the Jeffreys prior of its Remark 1. The paper does not name either parameter in code and calls neither dirichlet.
  • Equation 5 prints t - 1 in the denominator; the forecaster that sums to one over the labels of a node uses the count n of the samples of that node, which is what is implemented.
  • The label set grows with the stream: K is the number of labels seen so far, the current one included, unless classes fixes it as in the paper.
  • The input box is [low, high] on every feature; a value outside is clipped to the box, since the paper takes inputs in [0, 1]^d.
  • Prediction draws the splits that would separate the query from the sample of its cell and discards them (page 10), so predict_one is random; it never changes the trees.

Examples:

>>> from dense_armor.core.online.forest.amf import (
...     AggregatedMondrianForestClassifier,
... )
>>> f = AggregatedMondrianForestClassifier(n_trees=5, seed=0)
>>> for i in range(200):
...     x = (i % 20) / 19.0
...     _ = f.learn_one({"x": x}, 0 if x < 0.5 else 1)
>>> f.predict_one({"x": 0.1}), f.predict_one({"x": 0.9})
(0, 1)
References

Mourtada, J., Gaiffas, S., Scornet, E. AMF: Aggregated Mondrian forests for online learning. arXiv:1906.10529v2, the manuscript version of the PDF used. Equations 1, 5, 6, 7 and 9 to 11, Algorithms 2 and 3, Lemma 1, Corollaries 1 and 2. Lakshminarayanan, B., Roy, D. M., Teh, Y. W. (2014). Mondrian forests: efficient online random forests. In NIPS.

AggregatedMondrianForestClassifier

AggregatedMondrianForestClassifier(
    n_trees: int = 10,
    step: float = 1.0,
    dirichlet: float = 0.5,
    low: float = 0.0,
    high: float = 1.0,
    classes: list | None = None,
    seed: int | None = None,
    feature_keys: list | None = None,
    max_nodes: int | None = 10000,
)

Bases: _Forest, Classifier

Aggregated Mondrian forest classifier (Mourtada et al.).

Each of the n_trees trees predicts a distribution over the labels as the exponentially weighted average of all its prunings, with the Dirichlet forecaster (n_y + dirichlet) / (n + K * dirichlet) in every cell; the forest averages the trees.

Cost and memory. learn_one and predict_one walk one path of every tree down and up, a depth that grows like the logarithm of the number of samples (the paper states it for the restricted partition, page 11). A tree keeps two weights and a forecaster per node, and measured on uniform inputs in 1, 2 and 4 features it has 3.6 to 4.0 nodes per sample until max_nodes is reached. The limit bounds each tree, so the state is constant in the length of the stream and linear in n_trees, in max_nodes and in the number of features. There is no pure init_state / step form: the state is a tree that changes shape.

Parameters:

Name Type Description Default
n_trees int

number of trees M of the forest. Default 10.

10
step float

learning rate eta of the exponential weights. Default 1.0, the value of Corollary 1 for the logarithmic loss.

1.0
dirichlet float

symmetric Dirichlet parameter of the forecaster of a node. Default 0.5, the Krichevsky-Trofimov forecaster.

0.5
low float

lower end of every feature. Default 0.0.

0.0
high float

upper end of every feature. Default 1.0.

1.0
classes list | None

the label set, when known. None grows it with the stream.

None
seed int | None

seed of the generator of the partitions.

None
feature_keys list | None

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

None
max_nodes int | None

largest number of nodes of one tree. Default 10000. Once a tree has it, a new sample falls into the leaf of its cell, which keeps updating its weights and its forecaster, and the tree stops splitting. None lifts the limit. Below the limit the bounds of the paper hold; above it they are not claimed.

10000

Raises:

Type Description
ValueError

on a non-positive n_trees, step or dirichlet, or low >= high.

Examples:

>>> from dense_armor.core.online.forest.amf import (
...     AggregatedMondrianForestClassifier,
... )
>>> f = AggregatedMondrianForestClassifier(n_trees=3, seed=1)
>>> f.predict_one({"x": 0.5}) is None
True
>>> for i in range(40):
...     _ = f.learn_one({"x": (i % 2) * 0.8 + 0.1}, i % 2)
>>> f.predict_one({"x": 0.9})
1
References

Mourtada, Gaiffas, Scornet, Algorithms 2 and 3, Corollary 1.

Source code in dense_armor/core/online/forest/amf.py
def __init__(
    self,
    n_trees: int = 10,
    step: float = 1.0,
    dirichlet: float = 0.5,
    low: float = 0.0,
    high: float = 1.0,
    classes: list | None = None,
    seed: int | None = None,
    feature_keys: list | None = None,
    max_nodes: int | None = 10000,
) -> None:
    self._check(n_trees, step, low, high, max_nodes)
    if dirichlet <= 0.0:
        raise ValueError(f"dirichlet must be > 0, got {dirichlet}")
    self.max_nodes = max_nodes
    self.n_trees = n_trees
    self.step = step
    self.dirichlet = dirichlet
    self.low = low
    self.high = high
    self.classes = classes
    self.seed = seed
    self.feature_keys = feature_keys
    self.alphabet_: list = []
    self._setup()

learn_one

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

Add one labelled sample to every tree.

A sample without a label, with a missing or non-finite value, or a label outside classes is skipped and counted in n_missing.

Source code in dense_armor/core/online/forest/amf.py
def learn_one(
    self, x: Any, y: Any, t: float | None = None
) -> "AggregatedMondrianForestClassifier":
    """Add one labelled sample to every tree.

    A sample without a label, with a missing or non-finite value,
    or a label outside ``classes`` is skipped and counted in
    ``n_missing``.
    """
    self._time_step(t)
    d = _as_dict(x)
    v = self._vector(d) if d and y is not None else None
    if v is None or (self.classes is not None and y not in self.classes):
        self.n_missing_ += 1
        return self
    if not self.trees_:
        self.alphabet_.extend(self.classes if self.classes is not None else [])
        self._make_trees(len(v), _Frequency(self.dirichlet, self.alphabet_))
    self._share_alphabet()
    if y not in self.alphabet_:
        self.alphabet_.append(y)
    for tree in self.trees_:
        tree.add_point(v)
        tree.update_weights(v, y)
    self.n_seen_ += 1
    return self

predict_proba_one

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

Mean over the trees of the aggregated label distributions.

Source code in dense_armor/core/online/forest/amf.py
def predict_proba_one(self, x: Any, t: float | None = None) -> dict:
    """Mean over the trees of the aggregated label distributions."""
    return self._proba(x, True)

predict_one

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

Return the most probable label, or None before learning.

Source code in dense_armor/core/online/forest/amf.py
def predict_one(self, x: Any, t: float | None = None) -> Any:
    """Return the most probable label, or ``None`` before learning."""
    p = self.predict_proba_one(x, t=t)
    return max(p.items(), key=lambda kv: kv[1])[0] if p else None

predict_unaggregated_one

predict_unaggregated_one(x: Any) -> Any

Most probable label by the leaf forecasters alone, without aggregation.

Source code in dense_armor/core/online/forest/amf.py
def predict_unaggregated_one(self, x: Any) -> Any:
    """Most probable label by the leaf forecasters alone, without aggregation."""
    p = self._proba(x, False)
    return max(p.items(), key=lambda kv: kv[1])[0] if p else None

AggregatedMondrianForestRegressor

AggregatedMondrianForestRegressor(
    n_trees: int = 10,
    step: float = 0.125,
    low: float = 0.0,
    high: float = 1.0,
    seed: int | None = None,
    feature_keys: list | None = None,
    max_nodes: int | None = 10000,
)

Bases: _Forest, Regressor

Aggregated Mondrian forest regressor (Mourtada et al.).

Each tree predicts the exponentially weighted average, over all its prunings, of the empirical mean of the targets of the cell (0 for an empty cell, equation 4 of the paper, page 5), under the quadratic loss; the forest averages the trees. Cost and memory are those of :class:AggregatedMondrianForestClassifier.

Parameters:

Name Type Description Default
n_trees int

number of trees of the forest. Default 10.

10
step float

learning rate eta. Default 0.125, which is 1 / (8 B^2) of Corollary 2 for targets in [-1, 1]; for targets in [-B, B] pass 1 / (8 B^2).

0.125
low float

lower end of every feature. Default 0.0.

0.0
high float

upper end of every feature. Default 1.0.

1.0
seed int | None

seed of the generator of the partitions.

None
feature_keys list | None

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

None
max_nodes int | None

largest number of nodes of one tree. Default 10000; see :class:AggregatedMondrianForestClassifier.

10000

Raises:

Type Description
ValueError

on a non-positive n_trees or step, on max_nodes < 1, or low >= high.

Examples:

>>> from dense_armor.core.online.forest.amf import (
...     AggregatedMondrianForestRegressor,
... )
>>> f = AggregatedMondrianForestRegressor(n_trees=5, seed=0)
>>> f.predict_one({"x": 0.5})
0.0
>>> for i in range(300):
...     x = (i % 30) / 29.0
...     _ = f.learn_one({"x": x}, 1.0 if x > 0.5 else -1.0)
>>> f.predict_one({"x": 0.9}) > 0.5 > -0.5 > f.predict_one({"x": 0.1})
True
References

Mourtada, Gaiffas, Scornet, Algorithms 2 and 3, Corollary 2.

Source code in dense_armor/core/online/forest/amf.py
def __init__(
    self,
    n_trees: int = 10,
    step: float = 0.125,
    low: float = 0.0,
    high: float = 1.0,
    seed: int | None = None,
    feature_keys: list | None = None,
    max_nodes: int | None = 10000,
) -> None:
    self._check(n_trees, step, low, high, max_nodes)
    self.max_nodes = max_nodes
    self.n_trees = n_trees
    self.step = step
    self.low = low
    self.high = high
    self.seed = seed
    self.feature_keys = feature_keys
    self._setup()

learn_one

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

Add one sample to every tree.

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/amf.py
def learn_one(
    self, x: Any, y: Any, t: float | None = None
) -> "AggregatedMondrianForestRegressor":
    """Add one sample to every tree.

    A sample with a missing or non-finite value or target is skipped
    and counted in ``n_missing``.
    """
    self._time_step(t)
    d = _as_dict(x)
    try:
        target = float(y)
    except (TypeError, ValueError):
        target = math.nan
    v = self._vector(d) if d and math.isfinite(target) else None
    if v is None:
        self.n_missing_ += 1
        return self
    if not self.trees_:
        self._make_trees(len(v), _Mean())
    for tree in self.trees_:
        tree.add_point(v)
        tree.update_weights(v, target)
    self.n_seen_ += 1
    return self

predict_one

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

Mean over the trees of the aggregated predictions, 0.0 before learning.

Source code in dense_armor/core/online/forest/amf.py
def predict_one(
    self, x: Any, t: float | None = None, return_std: bool = False
) -> Any:
    """Mean over the trees of the aggregated predictions, 0.0 before learning."""
    out = self._value(x, True)
    return 0.0 if out is None else out

predict_unaggregated_one

predict_unaggregated_one(x: Any) -> float

Mean of the leaf forecasters alone, without aggregation.

Source code in dense_armor/core/online/forest/amf.py
def predict_unaggregated_one(self, x: Any) -> float:
    """Mean of the leaf forecasters alone, without aggregation."""
    out = self._value(x, False)
    return 0.0 if out is None else out

Details

The references, the choices the paper does not fix, the checks, the cost and the memory of the forests are in the Details of Streaming forests.