Decision trees and random forests

decision_tree and random_forest fit one tree or many, for a numeric outcome (regression) or for class labels (classification), on data that need not fit in memory.

import forest_stream as fs

# a numeric outcome: the mean of y within each leaf
fs.random_forest("price ~ area + rooms + age", "sales.parquet")

# class labels: probabilities and the likeliest class
fit = fs.random_forest("default ~ income + debt + age", "loans.parquet")
fit.predict("new_loans.parquet")     # class, prob_<label> for each label
fit.oob_score()                      # accuracy and log loss on rows a tree did not use

# one tree, shallow enough to read
tree = fs.decision_tree("default ~ income + debt + age", "loans.parquet", max_depth=4)
tree.tree()                          # one row per node: feature, threshold, children, value

Which function

Function

For

Trees

Honest by default

decision_tree

A tree you can read

One

No

random_forest

Prediction, with the usual random-forest defaults

Many, on samples of the rows

No

regression_forest

The conditional mean, with variances for the predictions

Many, on half-samples

Yes

causal_forest

How a treatment’s effect varies

Many, on half-samples

Yes

random_forest and regression_forest grow trees the same way. random_forest adds classification, sampling with replacement, honesty as a choice, max_depth and the usual random-forest defaults; regression_forest is always honest and samples without replacement, as the causal forest does.

Regression or classification

task="auto" fits a regression to a numeric outcome and a classification to a string, categorical or boolean outcome. An integer outcome is read as numeric; say task="classification" for integer class codes. A classification outcome may have up to 100 classes.

A classification forest averages the trees’ class proportions. predict returns the likeliest class and one prob_<label> column per class (and variance_<label> columns when variance_group_size is above 1). The probabilities of a forest grown to full depth on all of a tree’s sample tend to be too extreme; honesty (below), a max_depth, or a larger min_node_size give better calibrated ones.

criterion is "gini" or "entropy". Regression minimizes squared error.

How the rows are sampled

Each tree is grown on a sample of the rows, drawn by a rule that needs no record of which rows a tree has: whether a row is in a tree’s sample, and how many times, is a function of the row and the tree.

  • replace=True (the default for random_forest) draws each row a Poisson number of times, with mean sample_fraction (default 1). This is the Poisson bootstrap, the usual choice for streaming data; it differs from drawing exactly n rows with replacement only in that the sample size varies from tree to tree. A row is out of bag for a tree with probability exp(-sample_fraction).

  • replace=False draws each row at most once, with probability sample_fraction (default 0.632, the share of distinct rows in a bootstrap sample).

cluster= keeps all the rows of a group together: they are in a tree’s sample, or out of it, as one.

Honesty

With honesty=True, each tree’s sample is divided at random, by unit, into two parts. honesty_fraction of it (default one half) chooses the splits; the rest only estimates the values in the leaves. Leaves that none of the estimation rows reach are pruned. The estimates then do not reflect the noise that placed the splits, and a prediction’s sampling distribution is easier to describe. The cost is that each tree uses less of the data for each task. Without honesty, the same rows place the splits and estimate the leaves, as in Breiman’s random forests.

Splits

  • min_node_size: a node with fewer than twice this many rows is not split, and each child has at least this many. For random_forest the defaults follow the usual practice: 1 for classification and 5 for regression. decision_tree uses 5.

  • max_depth: the deepest level (the root is level 1). random_forest grows trees until nodes are pure or small; decision_tree stops at 6.

  • features_per_split: features tried at each split, chosen at random without replacement. The defaults are ceil(sqrt(p)) for classification and ceil(p / 3) for regression.

  • min_child_fraction: a split must leave each child at least this share of its parent’s rows (default 0).

Features are cut into at most max_bins (256) quantile bins once, and splits are made between bins. Continuous features with more than 256 distinct values are therefore split at quantile boundaries and not at every observed value.

Variances

A random forest gives no variance by default (variance_group_size=1). Set variance_group_size to 2 or more and its trees come in groups that share a half-sample, from which each prediction’s variance is estimated, as in causal_forest. Without replacement this needs sample_fraction of at most 0.5.

Out-of-bag scores

oob_score() predicts each row with the trees that did not use it, and returns the accuracy and log loss (classification) or the root mean squared error and R-squared (regression). oob_predictions() returns the predictions themselves, with the row_id of each row in the data.

Decision trees

decision_tree grows its tree one level at a time. Each level is one pass over the data that adds every row to histograms of the node it reaches, and the best split of each node comes from its histograms. A tree of max_depth levels therefore takes about max_depth passes, and memory grows with the number of nodes at a level, the number of features and the number of classes, not with the number of rows. If the histograms of a level do not fit in the memory left, the level is done in several passes.

tree() lists the nodes in depth-first order. A row goes to left when its feature is below threshold, and to right otherwise; leaves have no feature. n is the number of rows that estimate each node’s value, and prediction (regression) or class and prob_<label> (classification) its value.

The tree is grown on all the rows by default (sample_fraction=1, replace=False), so no row is out of bag; give sample_fraction below 1, or replace=True, to have rows to score it on, or score it on other data with predict. min_impurity_decrease stops a split that lowers the impurity (the variance, or the Gini impurity or entropy) by less than this much, weighted by the node’s share of the rows, as in scikit-learn.

Fixed effects

A regression or a decision tree of a numeric outcome takes fixed effects after a | and handles them as regression_forest does: see Fixed effects. random_forest and decision_tree accept fixed_effects="backfit", "outcome_within" and "group_means". Backfitting a decision tree uses the tree’s in-sample fitted values to update the group effects, since a tree grown on all the rows has none out of bag, so keep the tree shallow. Fixed effects are not available for classification.