Skip to content

Algorithms that work on the whole table by nature

← Machine learning

A desk keeps a table of orders and wants to know, from the size and the depth of the book, if a fill will be good. For some questions the answer is not a line: the fill is good when the size and the depth are on opposite sides of zero. A decision tree answers this by cutting the table in pieces, and it needs the whole table to choose its cuts. Three pieces of the library learn from the whole table in one call, the classic way, and sit next to their online counterparts so that the two ways can be run on the same data. A robot that must tell a stable run from an unstable one has the same kind of table.

The held-out accuracy of a decision tree, for 8 depths and 25 sizes of the table.

1. A first example: a tree on 400 orders

The fill is good when the size and the depth have opposite signs, which no single cut and no line can tell. The tree is fitted on 400 orders and judged on 400 fresh ones. The first number is the depth allowed to the tree, the second is the accuracy.

import numpy as np
from dense_armor.core.online.tree.batch import BatchDecisionTreeClassifier

rng = np.random.default_rng(0)
A = rng.normal(size=(800, 2))
X = [{"size": float(u), "depth": float(v)} for u, v in A]
y = [int((u > 0) != (v > 0)) for u, v in A]
for depth in (1, 4):
    m = BatchDecisionTreeClassifier(max_depth=depth).fit(X[:400], y[:400])
    hits = [m.predict_one(x) == t for x, t in zip(X[400:], y[400:])]
    print(depth, round(float(np.mean(hits)), 3))
1 0.463
4 0.973

A tree of depth 1 makes one cut on one feature, and no single cut tells the pair: it is at chance. A tree of depth 4 cuts twice and more and learns the rule.

The held-out accuracy of the tree against the size of the table, for three depths.

Over 5 tables, the median held-out accuracy reads 0.487 and 0.512 for a depth of 1 on tables of 85 and 800 orders, 0.535 and 0.667 for a depth of 2, 0.755 and 0.995 for a depth of 4, and 0.897 and 0.995 for a depth of 8. A greedy tree needs depth and rows for this kind of rule: with a depth of 2 it is still at 0.667 on 800 orders.

class or function what it does
BatchDecisionTreeClassifier a CART tree built from all the rows at once
OnlineBaggingClassifier.fit_batch fits each member of the ensemble on a bootstrap of the table
TextVectorizer builds the vocabulary and the document frequencies from a list of documents

2. What it does

BatchDecisionTreeClassifier builds a CART tree from all the rows at once. The sections below keep the three examples of the page as they were.

Source: Breiman, L., Friedman, J., Olshen, R., Stone, C. (1984). Classification and Regression Trees, chapter 2 (the gini impurity); Oza, N., Russell, S. (2001), section 2, page 2 (the batch protocol of bagging).

3. A decision tree on the whole training set

BatchDecisionTreeClassifier builds a CART tree from all the rows at once.

from dense_armor.core.online.tree.batch import BatchDecisionTreeClassifier

X = [{"x": 0.0}, {"x": 1.0}, {"x": 2.0}, {"x": 3.0}]
y = [0, 0, 1, 1]
clf = BatchDecisionTreeClassifier(max_depth=2).fit(X, y)
print(clf.predict_one({"x": 0.5}), clf.predict_one({"x": 2.5}))
0 1

At each node the tree takes the feature and the threshold with the lowest weighted gini impurity (Breiman, Friedman, Olshen and Stone, 1984, chapter 2). The tree is frozen when fit returns: learn_one after the fit leaves it unchanged. Its online counterpart is HoeffdingTreeClassifier, and Static vs online runs the two on the same stream with accuracy, time and memory.

4. Bagging fitted on bootstrap samples

OnlineBaggingClassifier.fit_batch fits each member on a bootstrap of the dataset, the same size with replacement, as in the batch protocol of Oza and Russell (2001), section 2, page 2.

from dense_armor.core.online.ensemble.bagging import OnlineBaggingClassifier
from dense_armor.core.online.tree.batch import BatchDecisionTreeClassifier

X = [{"x": float(i)} for i in range(8)]
y = [0, 0, 0, 0, 1, 1, 1, 1]
bag = OnlineBaggingClassifier(BatchDecisionTreeClassifier(max_depth=2), n_models=5, seed=0)
bag.fit_batch(X, y, seed=0)
print(bag.predict_one({"x": 1.0}), bag.predict_one({"x": 6.0}), len(bag.members_))
0 1 5

The row with x = 1.0 gets the class 0, the row with x = 6.0 the class 1, and the ensemble has five members. The online protocol, learn_one, gives each member a number of copies of each row drawn from a Poisson law with mean 1; the two protocols reach the same limit as the number of rows grows and differ on a finite sample. Each member is any estimator with a fit; with the batch tree as above, the whole ensemble works on the whole dataset.

5. Text: a vocabulary fitted on a list of documents

TextVectorizer.fit builds the vocabulary and the document frequencies from a list of documents; learn_one builds the same state one document at a time.

from dense_armor.core.signals.preprocessing.vectorizer import TextVectorizer

docs = ["the quick brown fox", "a quick brown dog", "the fox and the dog"]
a = TextVectorizer().fit(docs)
b = TextVectorizer()
for d in docs:
    b.learn_one(d)
print(a.tfidf_.n_docs_, a.tfidf_.df_ == b.tfidf_.df_)
3 True

The three documents, fitted in one call or learned one at a time, give the same number of documents and the same document frequency table. transform_matrix(docs) turns a list of documents into a sparse matrix of TF-IDF scores in one pass. The cosine ranking and the comparison with the batch library are on the page Text vectorizer.

6. The same on a robot

A robot has logged runs, each with a speed and a load, and a run is stable when the two are on opposite sides of their usual values.

import numpy as np
from dense_armor.core.online.tree.batch import BatchDecisionTreeClassifier

rng = np.random.default_rng(1)
A = rng.normal(size=(800, 2))
X = [{"speed": float(u), "load": float(v)} for u, v in A]
y = [int((u > 0) != (v > 0)) for u, v in A]
for depth in (1, 4):
    m = BatchDecisionTreeClassifier(max_depth=depth).fit(X[:400], y[:400])
    hits = [m.predict_one(x) == t for x, t in zip(X[400:], y[400:])]
    print(depth, round(float(np.mean(hits)), 3))
1 0.487
4 0.998

Again the tree of depth 1 is at chance and the deeper one learns the rule.

API reference

BatchDecisionTreeClassifier

BatchDecisionTreeClassifier(
    max_depth: int | None = None, min_samples_split: int = 2
)

Bases: Classifier

Batch CART classifier.

A binary decision tree trained on the whole dataset in one call to :meth:fit, with the gini impurity of Breiman, Friedman, Olshen and Stone (1984), chapter 2. The tree is built recursively: at each node, :func:_best_split scans every feature and every midpoint between consecutive sorted values, and the split that minimises the weighted gini impurity of the two children wins.

A node is a leaf when it is pure (one class), when max_depth is reached, when min_samples_split is not met, or when no split reduces the gini impurity. The prediction of a leaf is the majority class, ties broken by the smallest class.

This tree is the offline counterpart of :class:~dense_armor.core.online.tree.hoeffding.HoeffdingTreeClassifier. It is fitted on the whole training set once, and it never sees a sample after the fit. :meth:learn_one and :meth:predict_one after the fit are still available (the base class contract), but they do not change the tree: the tree is frozen at the end of :meth:fit. The two learners answer the same question with two protocols: one pass on the full training set (this class), one sample at a time (the online Hoeffding tree).

When a feature of the tree is missing from the dict given to :meth:predict_one or :meth:predict_proba_one, or its value is not a number, the answer is the majority class (the distribution) of the node where the path stops, and not of a leaf. budget_s is the budget of the per-sample calls (predict_one and learn_one), not of :meth:fit. memory_class describes the fitted tree; the memory check of check_estimator reads only "O(1)" and "O(window)", so it is skipped for this class.

Parameters:

Name Type Description Default
max_depth int | None

maximum depth of the tree. None means no limit.

None
min_samples_split int

minimum number of samples at a node to consider a split. Default 2 (a node with 2 samples can be split into two leaves of 1).

2

Examples:

>>> from dense_armor.core.online.tree.batch import BatchDecisionTreeClassifier
>>> X = [{"x": 0.0}, {"x": 1.0}, {"x": 2.0}, {"x": 3.0}]
>>> y = [0, 0, 1, 1]
>>> clf = BatchDecisionTreeClassifier(max_depth=2)
>>> _ = clf.fit(X, y)
>>> clf.predict_one({"x": 0.5})
0
>>> clf.predict_one({"x": 2.5})
1
Source code in dense_armor/core/online/tree/batch.py
def __init__(
    self,
    max_depth: int | None = None,
    min_samples_split: int = 2,
) -> None:
    if max_depth is not None and max_depth < 0:
        raise ValueError(f"max_depth must be >= 0, got {max_depth}")
    if min_samples_split < 2:
        raise ValueError(f"min_samples_split must be >= 2, got {min_samples_split}")
    self.max_depth = max_depth
    self.min_samples_split = min_samples_split
    self._root: _Node | None = None
    self._feature_names: list[str] = []

fit

fit(
    X: Any,
    y: Any = None,
    t: Any = None,
    epochs: int = 1,
    shuffle: bool = False,
    seed: int | None = None,
) -> BatchDecisionTreeClassifier

Fit the tree on the whole dataset.

Parameters:

Name Type Description Default
X Any

list of feature dicts.

required
y Any

list of labels, same length as X.

None
t Any

accepted for the interface of Root.fit; unused.

None
epochs int

accepted for the interface of Root.fit; unused.

1
shuffle bool

accepted for the interface of Root.fit; unused.

False
seed int | None

accepted for the interface of Root.fit; unused.

None

Returns:

Type Description
BatchDecisionTreeClassifier

self.

Raises:

Type Description
ValueError

on empty X, on y equal to None, on a length mismatch, on a row without one of the features of the first row, on a value that is not a number, or on a NaN or infinite value. The features are the keys of the first row; the other keys of the later rows are ignored.

Source code in dense_armor/core/online/tree/batch.py
def fit(
    self,
    X: Any,
    y: Any = None,
    t: Any = None,
    epochs: int = 1,
    shuffle: bool = False,
    seed: int | None = None,
) -> BatchDecisionTreeClassifier:
    """Fit the tree on the whole dataset.

    Args:
        X: list of feature dicts.
        y: list of labels, same length as ``X``.
        t: accepted for the interface of ``Root.fit``; unused.
        epochs: accepted for the interface of ``Root.fit``; unused.
        shuffle: accepted for the interface of ``Root.fit``; unused.
        seed: accepted for the interface of ``Root.fit``; unused.

    Returns:
        ``self``.

    Raises:
        ValueError: on empty ``X``, on ``y`` equal to ``None``, on a
            length mismatch, on a row without one of the features of
            the first row, on a value that is not a number, or on a
            NaN or infinite value. The features are the keys of the
            first row; the other keys of the later rows are ignored.
    """
    if y is None:
        raise ValueError("fit needs the labels y")
    if len(X) == 0:
        raise ValueError("cannot fit on an empty dataset")
    if len(X) != len(y):
        raise ValueError(f"X has {len(X)} rows, y has {len(y)}")
    feature_names = sorted(X[0].keys())
    rows = []
    for i, row in enumerate(X):
        try:
            rows.append([float(row[k]) for k in feature_names])
        except KeyError as err:
            raise ValueError(f"row {i} has no feature {err.args[0]!r}") from None
        except (TypeError, ValueError):
            raise ValueError(
                f"row {i} holds a value that is not a number"
            ) from None
    X_arr = as_default_array(rows)
    if not np.all(np.isfinite(X_arr)):
        raise ValueError("X holds a NaN or an infinite value")
    self._feature_names = feature_names
    y_arr = np.asarray(y)
    self._root = self._build(X_arr, y_arr, feature_names, 0)
    return self

predict_one

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

Majority class of the leaf that x reaches.

Source code in dense_armor/core/online/tree/batch.py
def predict_one(self, x: dict, t: float | None = None) -> Any:
    """Majority class of the leaf that ``x`` reaches."""
    leaf = self._predict_leaf(x)
    if leaf is None:
        return None
    return _majority(leaf.counts)

predict_proba_one

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

Class distribution of the leaf that x reaches.

Source code in dense_armor/core/online/tree/batch.py
def predict_proba_one(self, x: dict, t: float | None = None) -> dict:
    """Class distribution of the leaf that ``x`` reaches."""
    leaf = self._predict_leaf(x)
    if leaf is None:
        return {}
    total = sum(leaf.counts.values())
    if total == 0:
        return {}
    return {c: v / total for c, v in leaf.counts.items()}

learn_one

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

No-op after the fit; the tree is frozen.

Source code in dense_armor/core/online/tree/batch.py
def learn_one(
    self, x: dict, y: Any, t: float | None = None
) -> BatchDecisionTreeClassifier:
    """No-op after the fit; the tree is frozen."""
    return self

Details

Choices

  • The figures are drawn with the library by docs/assets/fit/make_fit_figures.py: tables of 20 to 800 orders and 400 fresh orders for the accuracy, the fill good when (size > 0) != (depth > 0), median over 5 seeds.