Skip to content

Bagging: a different sample for every member

← Ensembles

A desk learns whether a stock goes up from a daily signal. If every tree saw exactly the same days, they would make the same mistakes; bagging shows each tree the days a different number of times, so their mistakes differ and the vote of the group is steadier. A robot controller with the same problem is in the last section.

The running accuracy of a bag of five trees on a stock index, for 25 levels of noise in the signal.

1. A first example: a stock signal that separates two regimes

On calm days the signal is around 0 and the index falls; on strong days the signal is around 4 and it rises. The label is 1 when the signal is above 2. Five trees learn it from 500 days, each seeing a day a random number of times.

import numpy as np
from dense_armor.core.online.ensemble import OnlineBaggingClassifier
from dense_armor.core.online.tree.hoeffding import HoeffdingTreeClassifier

rng = np.random.default_rng(0)
bag = OnlineBaggingClassifier(
    lambda: HoeffdingTreeClassifier(grace_period=20), n_models=5, seed=1)
for _ in range(500):
    signal = float(rng.normal(0.0 if rng.random() < 0.5 else 4.0, 0.5))
    bag.learn_one({"signal": signal}, int(signal > 2.0))
print(bag.predict_one({"signal": 0.1}), bag.predict_one({"signal": 4.0}))
0 1

The Poisson draw is what makes the members differ. On the drifted stream of the cost section of the index the bag of five trees answers correctly more often than one tree in the median of 20 seeds (0.947 against 0.942, paired p = 0.003). The gain is small on this stream: the members share the same data, and the diversity the Poisson draw gives is limited.

A stock index with a noisy signal: the running accuracy of one tree and of a bag of five trees.

On a stock index with a signal of noise 0.8 the bag of five trees reads 0.714, 0.725 and 0.736 after 50, 150 and 300 days, and one tree reads 0.694, 0.658 and 0.672.

The picture follows the same 300 days of a stock index, where the desk sees a signal equal to the return plus a noise, for 25 levels of noise from 0.05 to 1.5. Each point of the surface is the running accuracy of the bag of five trees, scored before it learns each day. After 300 days it reads 0.967 for the noise 0.05, 0.736 for 0.78 and 0.595 for 1.5.

class what it does
OnlineBaggingClassifier members that train each sample a Poisson number of times

2. What the ensemble does

OnlineBaggingClassifier follows Oza and Russell (2001), Section 2. Every member sees every sample, but for each arriving sample it draws k from a Poisson(1) distribution and trains on the sample k times. On average a sample reaches each member once, and a few samples reach it twice or not at all, which is what a bootstrap sample of the batch algorithm does in the limit.

Source: Oza, N. C., Russell, S. (2001). Online bagging and boosting. In Artificial Intelligence and Statistics 2001, 105-112. Section 2 for the Poisson sampling.

The bagging counts are the part for which the paper proves that the expected counts of the online and batch algorithms are equal.

3. The parameters

Parameter Meaning Default
model a callable returning a fresh base classifier, or one classifier to clone; every member is built with it none
n_models number of members, at least one 10
seed seed of the Poisson draw; None uses a fresh random state None

OnlineBaggingClassifier raises ValueError if n_models < 1.

4. The same ensemble on a robot joint

A joint controller learns that a velocity qd above 2 is a fast joint (the label 1), from a stream where the velocity is around 0 or around 4.

import numpy as np
from dense_armor.core.online.ensemble import OnlineBaggingClassifier
from dense_armor.core.online.tree.hoeffding import HoeffdingTreeClassifier

rng = np.random.default_rng(0)
bag = OnlineBaggingClassifier(
    lambda: HoeffdingTreeClassifier(grace_period=20), n_models=5, seed=1)
for _ in range(500):
    qd = float(rng.normal(0.0 if rng.random() < 0.5 else 4.0, 0.5))
    bag.learn_one({"qd": qd}, int(qd > 2.0))
print(bag.predict_one({"qd": 0.1}), bag.predict_one({"qd": 4.0}))
0 1

A velocity of 0.1 is slow (0) and a velocity of 4.0 is fast (1).

API reference

OnlineBaggingClassifier

OnlineBaggingClassifier(
    model: Any, n_models: int = 10, seed: int | None = None
)

Bases: Classifier

Bagging of online classifiers with a Poisson(1) resample.

Every member is trained on the same stream, but for each arriving sample the class draws k ~ Poisson(1) and calls the member's learn_one k times. The prediction is a hard vote of the members; the probabilities are the mean of the members that expose predict_proba_one. See Oza and Russell (2001), Section 2.

Parameters:

Name Type Description Default
model Any

a callable returning a fresh base classifier, or a single classifier instance to clone. Every member is built with this.

required
n_models int

number of members. Must be at least one.

10
seed int | None

seed of the Poisson draw. None uses a fresh random state.

None

Raises:

Type Description
ValueError

if n_models < 1.

Examples:

>>> import numpy as np
>>> from dense_armor.core.online.tree.hoeffding import HoeffdingTreeClassifier
>>> from dense_armor.core.online.ensemble.bagging import OnlineBaggingClassifier
>>> rng = np.random.default_rng(0)
>>> clf = OnlineBaggingClassifier(
...     lambda: HoeffdingTreeClassifier(grace_period=20), n_models=3, seed=0)
>>> for _ in range(400):
...     x = float(rng.normal(0.0 if rng.random() < 0.5 else 4.0, 0.5))
...     y = int(x > 2.0)
...     _ = clf.learn_one({"x": x}, y)
>>> clf.predict_one({"x": 0.1}) != clf.predict_one({"x": 4.0})
True
Source code in dense_armor/core/online/ensemble/bagging.py
def __init__(self, model: Any, n_models: int = 10, seed: int | None = None) -> None:
    if n_models < 1:
        raise ValueError(f"n_models must be >= 1, got {n_models}")
    self.model = model
    self.n_models = int(n_models)
    self.seed = seed
    self._rng = np.random.default_rng(seed)
    self.members_: list = []
    self.classes_: set = set()
    self.n_seen_ = 0
    self.n_missing_ = 0

learn_one

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

Train every member k ~ Poisson(1) times on the sample.

Source code in dense_armor/core/online/ensemble/bagging.py
def learn_one(
    self, x: Any, y: Any, t: float | None = None
) -> "OnlineBaggingClassifier":
    """Train every member ``k ~ Poisson(1)`` times on the sample."""
    d = as_dict(x)
    if not d or y is None or not finite(d):
        self.n_missing_ += 1
        return self
    if not self.members_:
        self.members_ = [self._new_member() for _ in range(self.n_models)]
    self.classes_.add(y)
    for m in self.members_:
        k = int(self._rng.poisson(1.0))
        for _ in range(k):
            m.learn_one(d, y)
    self.n_seen_ += 1
    return self

fit_batch

fit_batch(
    X: list, y: list, seed: int | None = None
) -> OnlineBaggingClassifier

Batch entry point: fit each member on a bootstrap of (X, y).

This is the batch protocol of Oza and Russell 2001, section 2, page 2: for each member, draw a bootstrap of the whole dataset (same size, with replacement) and fit the member on that bootstrap. The members are then combined with the same vote of :meth:predict_one. The online protocol, :meth:learn_one, gives each member k ~ Poisson(1) copies of each sample instead; the two protocols have the same limit as N goes to infinity, and differ in expectation on a finite sample.

Parameters:

Name Type Description Default
X list

list of feature dicts, one per sample.

required
y list

list of labels, same length as X.

required
seed int | None

RNG seed for the bootstrap draws. None continues the generator of the estimator.

None

Returns:

Type Description
OnlineBaggingClassifier

self, fitted.

Raises:

Type Description
ValueError

if X and y have different lengths, or if X is empty.

Source code in dense_armor/core/online/ensemble/bagging.py
def fit_batch(
    self,
    X: list,
    y: list,
    seed: int | None = None,
) -> "OnlineBaggingClassifier":
    """Batch entry point: fit each member on a bootstrap of ``(X, y)``.

    This is the batch protocol of Oza and Russell 2001, section 2,
    page 2: for each member, draw a bootstrap of the whole dataset
    (same size, with replacement) and fit the member on that
    bootstrap. The members are then combined with the same vote of
    :meth:`predict_one`. The online protocol, :meth:`learn_one`,
    gives each member ``k ~ Poisson(1)`` copies of each sample
    instead; the two protocols have the same limit as N goes to
    infinity, and differ in expectation on a finite sample.

    Args:
        X: list of feature dicts, one per sample.
        y: list of labels, same length as ``X``.
        seed: RNG seed for the bootstrap draws. ``None`` continues the
            generator of the estimator.

    Returns:
        ``self``, fitted.

    Raises:
        ValueError: if ``X`` and ``y`` have different lengths, or
            if ``X`` is empty.
    """
    if len(X) != len(y):
        raise ValueError(f"X has {len(X)} rows, y has {len(y)}")
    if len(X) == 0:
        raise ValueError("cannot fit_batch on an empty dataset")
    if not self.members_:
        self.members_ = [
            self._new_member() for _ in range(self.n_models)
        ]
    for label in y:
        self.classes_.add(label)
    rng = self._rng if seed is None else np.random.default_rng(seed)
    n = len(X)
    for member in self.members_:
        idx_b = rng.integers(0, n, size=n)
        X_boot = [X[i] for i in idx_b]
        y_boot = [y[i] for i in idx_b]
        member.fit(X_boot, y_boot)
    self.n_seen_ += n
    return self

predict_proba_one

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

Mean of the members' probability dicts.

Source code in dense_armor/core/online/ensemble/bagging.py
def predict_proba_one(self, x: Any, t: float | None = None) -> dict:
    """Mean of the members' probability dicts."""
    if not self.members_:
        return {}
    d = as_dict(x)
    acc: dict = {}
    n_votes = 0
    for m in self.members_:
        try:
            p = m.predict_proba_one(d)
        except (AttributeError, TypeError):
            p = None
        if not p:
            continue
        n_votes += 1
        for c, v in p.items():
            acc[c] = acc.get(c, 0.0) + float(v)
    if n_votes == 0:
        return {}
    return {c: v / n_votes for c, v in acc.items()}

predict_one

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

Hard vote of the members; ties go to the smallest class.

Source code in dense_armor/core/online/ensemble/bagging.py
def predict_one(self, x: Any, t: float | None = None) -> Any:
    """Hard vote of the members; ties go to the smallest class."""
    if not self.members_:
        return None
    d = as_dict(x)
    votes: dict = {}
    for m in self.members_:
        try:
            p = m.predict_one(d)
        except (AttributeError, TypeError):
            p = None
        if p is None:
            continue
        votes[p] = votes.get(p, 0) + 1
    if not votes:
        return None
    return max(sorted(votes), key=lambda c: votes[c])

Details

Choices

  • The Poisson draw of bagging. The paper draws Poisson(1) per member per sample. The class draws one k per member and calls learn_one k times, which is the same rule.