Estimation¶
- forest_stream.causal_forest(fml, data, *, cluster=None, weights=None, num_trees=2000, min_node_size=5, features_per_split=None, min_treatment_variation=0.05, sample_fraction=0.5, honesty_fraction=0.5, variance_group_size=2, max_bins=256, nuisance='forest', fixed_effects='backfit', fixef_rm='none', max_iterations=100, backfit_tolerance=0.1, backfit_warm_start=True, nuisance_num_trees=None, max_memory_gb=None, memory_reserve=None, workdir=None, keep_workdir=False, n_threads=None, seed=0, profile=False, verbose=False)[source]¶
Fit an honest causal forest for heterogeneous treatment effects.
- Parameters:
fml (str) –
"y ~ w | x1 + x2 + x3": the outcome, the treatment, and the features that the effect may depend on. Fixed effects, if any, follow a second|:"y ~ w | x1 + x2 | worker + firm". Names are plain columns.data (str, polars.DataFrame or polars.LazyFrame) – A Parquet path or glob, or a frame.
cluster (str, optional) – A column whose values are sampled together: all rows of a cluster are in or out of a tree’s sample.
weights (str, optional) – A column of sample weights (analytic weights: positive, finite, and independent of the outcome given the features). The splits, the values in the leaves, the effect estimates and their inference are weighted, and so are the regressions on the fixed effects; the sampling of rows into trees is not, and sizes (
min_node_size) count rows. Rows with a zero weight are left out; a negative weight is an error. Scaling all the weights by a constant changes nothing.num_trees (int, default 2000) – Trees, rounded up to a multiple of
variance_group_size.min_node_size (int, default 5) – The fewest rows of a tree’s splitting sample in a leaf.
features_per_split (int, optional) – The mean number of features tried at a split (the number is drawn from a Poisson distribution). Default
min(ceil(sqrt(p) + 20), p)for p features.min_treatment_variation (float, default 0.05) – A split must leave each child at least this share of the parent’s variation in the treatment.
sample_fraction (float, default 0.5) – The share of rows (or clusters) in each tree’s sample. At most 0.5 when
variance_group_sizeis above 1.honesty_fraction (float, default 0.5) – The share of a tree’s sample used to place its splits; the rest estimates the effect in its leaves.
variance_group_size (int, default 2) – Trees per group sharing a half-sample, from which the variance of the estimates is computed (little bags). Use 1 to skip variances.
max_bins (int, default 256) – Bins per feature (at most 256). Splits are placed at quantile bin boundaries of the features.
nuisance ({"forest", "linear"}, default "forest") – How the outcome and the treatment are centered before the causal forest is grown.
"forest"estimates their conditional means given the features (and the fixed effects) with out-of-bag regression forests, and subtracts them."linear"subtracts the fixed effects and a linear function of the features, with one hdfe-stream fit: much faster, and adequate when the outcome and treatment are close to linear in the features.fixed_effects – With
nuisance="forest"and fixed effects in the formula, how the fixed effects enter the two nuisance forests: see below."group_means"is not available for causal forests; usenuisance="linear"for a fast alternative.fixef_rmis as inregression_forest.max_iterations(default 100) andbackfit_tolerance(default 0.1, a fraction of the effects’ standard error) stop the backfitting; seeregression_forest.fixef_rm – With
nuisance="forest"and fixed effects in the formula, how the fixed effects enter the two nuisance forests: see below."group_means"is not available for causal forests; usenuisance="linear"for a fast alternative.fixef_rmis as inregression_forest.max_iterations(default 100) andbackfit_tolerance(default 0.1, a fraction of the effects’ standard error) stop the backfitting; seeregression_forest.max_iterations – With
nuisance="forest"and fixed effects in the formula, how the fixed effects enter the two nuisance forests: see below."group_means"is not available for causal forests; usenuisance="linear"for a fast alternative.fixef_rmis as inregression_forest.max_iterations(default 100) andbackfit_tolerance(default 0.1, a fraction of the effects’ standard error) stop the backfitting; seeregression_forest.backfit_tolerance – With
nuisance="forest"and fixed effects in the formula, how the fixed effects enter the two nuisance forests: see below."group_means"is not available for causal forests; usenuisance="linear"for a fast alternative.fixef_rmis as inregression_forest.max_iterations(default 100) andbackfit_tolerance(default 0.1, a fraction of the effects’ standard error) stop the backfitting; seeregression_forest.backfit_warm_start – With
nuisance="forest"and fixed effects in the formula, how the fixed effects enter the two nuisance forests: see below."group_means"is not available for causal forests; usenuisance="linear"for a fast alternative.fixef_rmis as inregression_forest.max_iterations(default 100) andbackfit_tolerance(default 0.1, a fraction of the effects’ standard error) stop the backfitting; seeregression_forest.nuisance_num_trees (int, optional) – Trees in each nuisance forest (and in each backfitting round). Default
max(200, num_trees / 4).max_memory_gb (float, optional) – The memory the fit may use. Default: what the process may use (the job’s limit, or the machine’s memory). The trees are grown in batches sized to what is left after
memory_reserveand what the process already holds; a smaller budget means more passes over the data.memory_reserve (float, optional) – The share of
max_memory_gbkept back for what the model does not count. Default 0.15.workdir (str, optional) – The directory in which the fit makes its own run directory. Default: the system’s temporary directory. Nothing else in it is touched.
keep_workdir (bool, default False) – Keep the run directory after the result is gone.
n_threads (int, optional) – Threads for the compiled passes. Default: all that the job may use.
seed (int, default 0) – The seed. The same seed gives the same forest whatever
n_threads, up to rounding in the last digits.profile (bool, default False) – Return the expected memory and disk of the fit, as a
hdfe_stream.core.profile.Profile, after one streaming scan of the data and without fitting.verbose (bool, default False) – Print progress.
- forest_stream.instrumental_forest(fml, data, *, instrument, cluster=None, weights=None, num_trees=2000, min_node_size=5, features_per_split=None, min_treatment_variation=0.05, sample_fraction=0.5, honesty_fraction=0.5, variance_group_size=2, max_bins=256, nuisance='forest', fixed_effects='backfit', fixef_rm='none', max_iterations=100, backfit_tolerance=0.1, backfit_warm_start=True, nuisance_num_trees=None, max_memory_gb=None, memory_reserve=None, workdir=None, keep_workdir=False, n_threads=None, seed=0, profile=False, verbose=False)[source]¶
Fit an honest instrumental forest: how the effect of a treatment that people choose, among those whom an instrument moves, varies with their features.
The formula and the options are those of
causal_forest, with one more: the instrument, a column that moves the treatment and affects the outcome only through it. A forest grown with the instrument as the treatment’s stand-in finds the splits where the instrument’s effect on the outcome and on the treatment, together, change; each leaf’s estimate is the ratio of those two effects. The outcome, the treatment and the instrument are centered on the features (and the fixed effects) first, as incausal_forest; withnuisance="forest"that is three out-of-bag forests.- Parameters:
fml (str) –
"y ~ w | x1 + x2"or"y ~ w | x1 + x2 | worker + firm", as forcausal_forest.data (str, polars.DataFrame or polars.LazyFrame)
instrument (str) – The column of the instrument (binary or continuous). It is not one of the formula’s columns.
**options – As
causal_forest;min_treatment_variationis the share of the parent’s variation in the instrument that each child must keep.
- Returns:
InstrumentalForestResult – As
CausalForestResult, with the effects being the local effects of the treatment;calibration_testis not available.
- forest_stream.quantile_forest(fml, data, *, quantiles=(0.1, 0.5, 0.9), cluster=None, weights=None, num_trees=2000, min_node_size=5, features_per_split=None, min_child_fraction=0.05, sample_fraction=0.5, honesty_fraction=0.5, max_bins=256, max_memory_gb=None, memory_reserve=None, workdir=None, keep_workdir=False, n_threads=None, seed=0, verbose=False)[source]¶
Fit an honest quantile forest: the conditional quantiles of an outcome.
Each tree keeps the outcomes of its estimation rows, leaf by leaf, so any quantile can be read off afterwards: a row’s quantile is the weighted quantile of the outcomes in the leaves it falls in, over all the trees (Meinshausen 2006). Trees are grown to separate rows whose outcome distributions differ at the chosen quantiles (Athey, Tibshirani and Wager 2019).
- Parameters:
fml (str) –
"y ~ x1 + x2 + x3": the outcome and the features. Fixed effects are not available.data (str, polars.DataFrame or polars.LazyFrame) – A Parquet path or glob, or a frame.
quantiles (sequence of float, default (0.1, 0.5, 0.9)) – The levels the trees are grown to separate, strictly between 0 and 1. Choose the levels that matter: a forest grown for the tails and the median estimates them better than one grown for the median alone.
predictcan ask for other levels, which the trees were not grown for.cluster
weights
num_trees
min_node_size
features_per_split
min_child_fraction
sample_fraction
honesty_fraction
max_bins
max_memory_gb
memory_reserve
workdir – As in
regression_forest. There are no variance groups: a quantile forest has no variance estimate.keep_workdir – As in
regression_forest. There are no variance groups: a quantile forest has no variance estimate.n_threads – As in
regression_forest. There are no variance groups: a quantile forest has no variance estimate.seed – As in
regression_forest. There are no variance groups: a quantile forest has no variance estimate.verbose – As in
regression_forest. There are no variance groups: a quantile forest has no variance estimate.
- Returns:
QuantileForestResult
Notes
Rows with a missing or infinite value in any column used are dropped. The forest stores the outcomes of every tree’s estimation rows on disk, about
num_trees * n * sample_fraction * (1 - honesty_fraction)values of 8 bytes.
- forest_stream.regression_forest(fml, data, *, cluster=None, weights=None, num_trees=2000, min_node_size=5, features_per_split=None, min_child_fraction=0.05, sample_fraction=0.5, honesty_fraction=0.5, variance_group_size=2, max_bins=256, fixed_effects='backfit', fixef_rm='none', max_iterations=100, backfit_tolerance=0.1, backfit_warm_start=True, backfit_num_trees=None, max_memory_gb=None, memory_reserve=None, workdir=None, keep_workdir=False, n_threads=None, seed=0, profile=False, verbose=False)[source]¶
Fit an honest regression forest: the conditional mean of an outcome.
- Parameters:
fml (str) –
"y ~ x1 + x2 + x3": the outcome and the features. Fixed effects, if any, follow a|:"y ~ x1 + x2 | firm". Names are plain columns.data (str, polars.DataFrame or polars.LazyFrame) – A Parquet path or glob, or a frame.
cluster (str, optional) – A column whose values are sampled together: all rows of a cluster are in or out of a tree’s sample.
weights (str, optional) – A column of sample weights (analytic weights: positive, finite, and independent of the outcome given the features). The splits, the values in the leaves, the effect estimates and their inference are weighted, and so are the regressions on the fixed effects; the sampling of rows into trees is not, and sizes (
min_node_size) count rows. Rows with a zero weight are left out; a negative weight is an error. Scaling all the weights by a constant changes nothing.num_trees (int, default 2000) – Trees, rounded up to a multiple of
variance_group_size.min_node_size (int, default 5) – The fewest rows of a tree’s splitting sample in a leaf.
features_per_split (int, optional) – The mean number of features tried at a split (the number is drawn from a Poisson distribution). Default
min(ceil(sqrt(p) + 20), p)for p features.min_child_fraction (float, default 0.05) – A split must leave each child at least this share of the parent’s rows.
sample_fraction – As in
causal_forest.honesty_fraction – As in
causal_forest.variance_group_size – As in
causal_forest.max_bins – As in
causal_forest.fixed_effects ({"backfit", "outcome_within", "group_means"}, default "backfit") –
How the fixed effects are handled, when the formula has any. The model is
y = g(x) + alpha_group + e, and the forest estimatesg, so predictions are net of the group effects."backfit"alternates a forest and the group effects: a forest is fitted toyless the current effects, its out-of-bag predictions are subtracted fromy, and the effects are re-estimated from what is left (hdfe-stream), until they change by less thanbackfit_tolerancetimes their own standard error ormax_iterationsrounds have run (a warning says so when they have). It is right when the features are related to the groups, at the cost of several forests and several hdfe-stream fits."outcome_within"subtracts the groups’ means of the outcome once, and fits the forest to the result. It assumes that the features are unrelated to the groups: when they are not, the forest estimates the wrong function, and more data does not help. The share of each feature’s variance that lies between groups is inbetween_group_share, with a warning when it exceeds 10 percent."group_means"leaves the outcome alone and adds each group’s mean of each feature, for each fixed effect, as further features, so the forest can learn the part of the group effect that those means explain. It is the fastest, but it estimates something else:E[y | x, the groups' feature means], which includes that part of the group effect, with the rest of it in the error. Rows are sampled by group (thecluster; by default the fixed effect, when there is one), so the variances allow for that. Predictions need the fixed-effect columns in the data, and groups seen when the forest was fitted.fixef_rm ({"none", "singleton"}, default "none") – Whether the group effects are estimated from the rows that are alone in one of their groups.
"none"keeps them: each such row gets an effect of its own, which fits its outcome exactly."singleton"leaves them out, as hdfe-stream’s regressions do: the fit uses only groups with two or more rows, and a dropped row gets no group effect (it is treated as a group not seen at fit when predicting).fit.backfit["singletons_dropped"]counts them.max_iterations (int, default 100) – The most backfitting rounds.
backfit_tolerance (float, default 0.1) – Backfitting stops when the group effects change, from one round to the next, by less than this fraction of their standard error (root mean square over rows; the standard error is
sigma * sqrt(rank / rows)for the residuals’ standard deviation and the number of parameters of the fixed effects). Changes much below the standard error cannot matter to anything estimated from the effects. The forests’ own sampling noise makes the changes level off at a few percent of it, so values much below 0.05 stop at that level, which counts as converged.backfit_warm_start (bool, default True) – Whether the backfitting rounds after the first keep the first round’s trees and estimate their leaf values again on the new residual, which is much cheaper than growing the trees again. Accuracy and coverage are unchanged in our simulations;
Falsegrows every round’s trees afresh.backfit_num_trees (int, optional) – Trees in each backfitting round’s forest. Default
max(100, num_trees / 4). The final forest hasnum_trees.max_memory_gb – As in
causal_forest.memory_reserve – As in
causal_forest.workdir – As in
causal_forest.keep_workdir – As in
causal_forest.n_threads – As in
causal_forest.seed – As in
causal_forest.profile – As in
causal_forest.verbose – As in
causal_forest.
- Returns:
RegressionForestResult or Profile
Notes
Rows with a missing or infinite value in any column used are dropped.
- forest_stream.random_forest(fml, data, *, task='auto', cluster=None, weights=None, num_trees=500, min_node_size=None, node_size_rule='split', features_per_split=None, min_child_fraction=0.0, max_depth=None, criterion='gini', sample_fraction=None, replace=True, honesty=False, honesty_fraction=0.5, variance_group_size=1, max_bins=256, fixed_effects='backfit', fixef_rm='none', max_iterations=100, backfit_tolerance=0.1, backfit_warm_start=True, backfit_num_trees=None, max_memory_gb=None, memory_reserve=None, workdir=None, keep_workdir=False, n_threads=None, seed=0, profile=False, verbose=False)[source]¶
Fit a random forest: trees grown on random samples of the rows, each split choosing among a random subset of the features, with predictions averaged over the trees.
- Parameters:
fml (str) –
"y ~ x1 + x2 + x3": the outcome and the features. Fixed effects for a numeric outcome follow a|:"y ~ x1 + x2 | firm".data (str, polars.DataFrame or polars.LazyFrame) – A Parquet path or glob, or a frame.
task ({"auto", "regression", "classification"}, default "auto") – A numeric outcome is regression and a string, categorical or boolean outcome is classification. Say
"classification"for integer class codes.cluster (str, optional) – A column whose values are sampled together.
weights (str, optional) – A column of sample weights (analytic weights: positive, finite, and independent of the outcome given the features). The splits, the values in the leaves, the effect estimates and their inference are weighted, and so are the regressions on the fixed effects; the sampling of rows into trees is not, and sizes (
min_node_size) count rows. Rows with a zero weight are left out; a negative weight is an error. Scaling all the weights by a constant changes nothing.num_trees (int, default 500) – Trees, rounded up to a multiple of
variance_group_size.min_node_size (int, optional) – The target size of the leaves;
node_size_rulesays how it is enforced. Default 5 for regression, 1 for classification.node_size_rule ({"split", "leaf"}, default "split") –
"split": a node with at mostmin_node_sizerows is not split, and the children of a split may be of any size, so leaves can be smaller thanmin_node_size(the rule of ranger, R’s randomForest and grf)."leaf": a node with fewer than twicemin_node_sizerows is not split and every child has at least that many (the rule of scikit-learn’smin_samples_leafand rpart’sminbucket).features_per_split (int, optional) – Features tried at each split, chosen at random without replacement. Default
ceil(sqrt(p))for classification andceil(p / 3)for regression, for p features.min_child_fraction (float, default 0) – A split must leave each child at least this share of the parent’s rows.
max_depth (int, optional) – The deepest level of a tree (the root is level 1). Default: grown until nodes are pure or too small.
criterion ({"gini", "entropy"}, default "gini") – The split criterion for classification. Regression minimizes squared error.
sample_fraction (float, optional) – The expected number of draws per tree, as a share of the rows. Default 1 with replacement, 0.632 without (the share of distinct rows in a bootstrap sample).
replace (bool, default True) – Sample with replacement (a bootstrap) or without. With replacement, each row is drawn a Poisson number of times with the mean that
sample_fractionimplies (the Poisson bootstrap, which needs no record of which rows a tree drew), so a tree’s sample size is random and a row is out of bag for a tree with probabilityexp(-sample_fraction).honesty (bool, default False) – Estimate each leaf from rows other than those that placed the splits: a tree’s sample is divided at random, and
honesty_fractionof its units place the splits. Leaves that no estimation row reaches are pruned. Without it, leaves average the rows that grew them.honesty_fraction (float, default 0.5) – The share of a tree’s sample used to place its splits, with
honesty.variance_group_size (int, default 1) – With more than 1, trees come in groups sharing a half-sample, from which the variance of each prediction is computed (little bags, as in
causal_forest). Without replacement this needssample_fractionof at most 0.5.max_bins (int, default 256) – Bins per feature (at most 256).
fixed_effects – For a numeric outcome with fixed effects in the formula: see
regression_forest. Not available for classification.fixef_rm – For a numeric outcome with fixed effects in the formula: see
regression_forest. Not available for classification.max_iterations – For a numeric outcome with fixed effects in the formula: see
regression_forest. Not available for classification.backfit_tolerance – For a numeric outcome with fixed effects in the formula: see
regression_forest. Not available for classification.backfit_warm_start – For a numeric outcome with fixed effects in the formula: see
regression_forest. Not available for classification.backfit_num_trees – For a numeric outcome with fixed effects in the formula: see
regression_forest. Not available for classification.max_memory_gb – As in
causal_forest.memory_reserve – As in
causal_forest.workdir – As in
causal_forest.keep_workdir – As in
causal_forest.n_threads – As in
causal_forest.seed – As in
causal_forest.profile – As in
causal_forest.verbose – As in
causal_forest.
- Returns:
RandomForestResult or ClassificationForestResult or Profile
- forest_stream.decision_tree(fml, data, *, task='auto', cluster=None, weights=None, max_depth=6, min_node_size=5, node_size_rule='leaf', min_child_fraction=0.0, min_impurity_decrease=0.0, criterion='gini', sample_fraction=1.0, replace=False, honesty=False, honesty_fraction=0.5, max_bins=256, fixed_effects='backfit', fixef_rm='none', max_iterations=100, backfit_tolerance=0.1, backfit_warm_start=True, max_memory_gb=None, memory_reserve=None, workdir=None, keep_workdir=False, n_threads=None, seed=0, profile=False, verbose=False)[source]¶
Fit one decision tree.
The tree is grown level by level from histograms of the features, accumulated in one streaming pass over the data per level, so the rows need not fit in memory;
max_depthlimits the passes and the memory. Every feature is considered at every split.- Parameters:
fml (str) –
"y ~ x1 + x2 + x3": the outcome and the features. Fixed effects for a numeric outcome follow a|:"y ~ x1 + x2 | firm".data (str, polars.DataFrame or polars.LazyFrame) – A Parquet path or glob, or a frame.
task ({"auto", "regression", "classification"}, default "auto") – As in
random_forest.cluster (str, optional) – A column whose values are sampled together (relevant when the tree is grown on a sample).
weights (str, optional) – A column of sample weights (analytic weights: positive, finite, and independent of the outcome given the features). The splits, the values in the leaves and the regressions on the fixed effects are weighted; the sampling of rows into the tree is not, and sizes (
min_node_size) count rows. Rows with a zero weight are left out; a negative weight is an error. Scaling all the weights by a constant changes nothing.max_depth (int, default 6) – The deepest level of the tree (the root is level 1).
min_node_size (int, default 5) – The target size of the leaves;
node_size_rulesays how it is enforced.node_size_rule ({"leaf", "split"}, default "leaf") –
"leaf": a node with fewer than twicemin_node_sizerows is not split and every child has at least that many (scikit-learn’smin_samples_leaf, rpart’sminbucket)."split": a node with at mostmin_node_sizerows is not split, and children may be of any size (ranger, randomForest, grf).min_child_fraction (float, default 0) – A split must leave each child at least this share of the parent’s rows.
min_impurity_decrease (float, default 0) – A split must lower the impurity (the variance of the outcome, the Gini impurity or the entropy) by at least this much, weighted by the node’s share of the rows, as in scikit-learn.
criterion ({"gini", "entropy"}, default "gini") – The split criterion for classification. Regression minimizes squared error.
sample_fraction (float, default 1) – The share of the rows the tree is grown on (the expected number of draws, with replacement).
replace (bool, default False) – Sample with replacement (a Poisson bootstrap) or without.
honesty (bool, default False) – Place the splits with
honesty_fractionof the sample and estimate the leaves from the rest; leaves no estimation row reaches are pruned.honesty_fraction (float, default 0.5) – The share of the sample that places the splits, with
honesty.max_bins (int, default 256) – Bins per feature (at most 256).
fixed_effects – For a numeric outcome with fixed effects in the formula: see
regression_forest. The rounds of backfitting grow a tree on the rows and use its in-sample fitted values to update the effects, so the tree should be shallow. Not available for classification.fixef_rm – For a numeric outcome with fixed effects in the formula: see
regression_forest. The rounds of backfitting grow a tree on the rows and use its in-sample fitted values to update the effects, so the tree should be shallow. Not available for classification.max_iterations – For a numeric outcome with fixed effects in the formula: see
regression_forest. The rounds of backfitting grow a tree on the rows and use its in-sample fitted values to update the effects, so the tree should be shallow. Not available for classification.backfit_tolerance – For a numeric outcome with fixed effects in the formula: see
regression_forest. The rounds of backfitting grow a tree on the rows and use its in-sample fitted values to update the effects, so the tree should be shallow. Not available for classification.backfit_warm_start – For a numeric outcome with fixed effects in the formula: see
regression_forest. The rounds of backfitting grow a tree on the rows and use its in-sample fitted values to update the effects, so the tree should be shallow. Not available for classification.max_memory_gb – As in
causal_forest.memory_reserve – As in
causal_forest.workdir – As in
causal_forest.keep_workdir – As in
causal_forest.n_threads – As in
causal_forest.seed – As in
causal_forest.profile – As in
causal_forest.verbose – As in
causal_forest.
- Returns:
DecisionTreeResult or ClassificationTreeResult or Profile