Source code for forest_stream.api

"""The forest estimators."""

from __future__ import annotations

import dataclasses
import time
import warnings

import numpy as np
import polars as pl
from hdfe_stream.core.profile import Profile
from hdfe_stream.core.utils import as_lazy

from . import _fe
from ._formula import parse_forest_formula
from ._memory import forest_profile
from .centering import centering_formula, residualize_hdfe
from .forest import ForestEngine
from .results import (
    CausalForestResult,
    ClassificationForestResult,
    ClassificationTreeResult,
    DecisionTreeResult,
    InstrumentalForestResult,
    QuantileForestResult,
    RandomForestResult,
    RegressionForestResult,
)


def _check_fixed_effects(mode, terms, allowed):
    if mode not in allowed:
        raise ValueError(f"fixed_effects must be one of {allowed}, not {mode!r}")
    return mode if terms else None


def _make_engine(kind, o, workdir, keep_workdir, verbose, **over):
    keys = (
        "num_trees min_node_size features_per_split sample_fraction honesty_fraction "
        "variance_group_size max_bins max_memory_gb memory_reserve seed"
    ).split()
    kw = {k: o[k] for k in keys}
    knob = "min_treatment_variation" if kind in ("causal", "instrumental") else "min_child_fraction"
    kw[knob] = o[knob]
    kw.update(over)
    return ForestEngine(
        kind=kind, workdir=workdir, keep_workdir=keep_workdir, verbose=verbose, **kw
    )


def _round_engine(e, trees):
    """A factory of the regression engines that the backfitting rounds (and the
    nuisance forests) use: fewer trees, no variance groups, the same seed (so
    the rounds differ only by the outcome they are fitted to)."""

    def make(seed=None, trees=trees):
        if e.single_tree:
            return ForestEngine(
                kind="regression",
                target="y",
                num_trees=1,
                single_tree=True,
                min_node_size=e.min_node_size,
                sample_fraction=e.sample_fraction,
                honesty_fraction=e.honesty_fraction,
                variance_group_size=1,
                replace=e.replace,
                honesty=e.honesty,
                max_depth=e.max_depth,
                node_size_rule=e.node_size_rule,
                min_child_fraction=e.min_child_fraction,
                min_impurity_decrease=e.min_impurity_decrease,
                max_bins=e.max_bins,
                max_memory_gb=e.max_memory_gb,
                memory_reserve=e.memory_reserve,
                chunk_rows=e.chunk_rows,
                seed=e.seed if seed is None else e.seed + seed,
                verbose=False,
            )
        return ForestEngine(
            kind="regression",
            target="y",
            num_trees=trees,
            min_node_size=e.min_node_size,
            features_per_split=e.features_per_split,
            sample_fraction=e.sample_fraction,
            honesty_fraction=e.honesty_fraction,
            variance_group_size=1,
            replace=e.replace,
            honesty=e.honesty,
            max_depth=e.max_depth,
            poisson_features=e.poisson_features,
            node_size_rule=e.node_size_rule,
            min_child_fraction=e.min_child_fraction,
            max_bins=e.max_bins,
            max_memory_gb=e.max_memory_gb,
            memory_reserve=e.memory_reserve,
            chunk_rows=e.chunk_rows,
            seed=e.seed if seed is None else e.seed + seed,
            verbose=False,
        )

    return make


def _group_trees(n, group):
    return -(-n // group) * group


def _diagnostics(bf):
    return {
        "iterations": bf.iterations,
        "converged": bf.converged,
        "stopped": bf.stopped,
        "changes": list(bf.changes),
        "changes_abs": list(bf.changes_abs),
        "scale": bf.scale,
        "scale_kind": bf.scale_kind,
        "noise": bf.noise,
        "sigma": bf.sigma,
        "seconds": bf.seconds,
        "forest_seconds": bf.forest_seconds,
        "effects_seconds": bf.effects_seconds,
        "singletons_dropped": bf.dropped,
    }


def _residual(bf, store, path, chunk_rows):
    """The nuisance residual y0 - effects - out-of-bag fitted values."""
    y0 = np.load(bf.y0, mmap_mode="r")
    a = np.load(bf.effects, mmap_mode="r")
    g = np.load(bf.fitted, mmap_mode="r")
    out = _fe._memmap(path, store.n)
    for s in range(0, store.n, chunk_rows):
        out[s : s + chunk_rows] = (
            y0[s : s + chunk_rows] - a[s : s + chunk_rows] - g[s : s + chunk_rows]
        )
    out.flush()
    del out
    return path


def _set_treatment_and_outcome(store, w_path, y_path, chunk_rows, z_path=None):
    """Replace the store's treatment and outcome columns (and the instrument,
    given its residuals) by the residuals."""
    mm = np.memmap(store.path / "wy.f64", dtype=np.float64, mode="r+", shape=(store.n, 2))
    w = np.load(w_path, mmap_mode="r")
    y = np.load(y_path, mmap_mode="r")
    for s in range(0, store.n, chunk_rows):
        mm[s : s + chunk_rows, 0] = w[s : s + chunk_rows]
        mm[s : s + chunk_rows, 1] = y[s : s + chunk_rows]
    mm.flush()
    del mm
    if z_path is not None:
        zm = np.memmap(store.path / "z.f64", dtype=np.float64, mode="r+", shape=(store.n,))
        z = np.load(z_path, mmap_mode="r")
        for s in range(0, store.n, chunk_rows):
            zm[s : s + chunk_rows] = z[s : s + chunk_rows]
        zm.flush()
        del zm


[docs] def causal_forest( fml: str, data, *, cluster: str | None = None, weights: str | None = None, num_trees: int = 2000, min_node_size: int = 5, features_per_split: int | None = None, min_treatment_variation: float = 0.05, sample_fraction: float = 0.5, honesty_fraction: float = 0.5, variance_group_size: int = 2, max_bins: int = 256, nuisance: str = "forest", fixed_effects: str = "backfit", fixef_rm: str = "none", max_iterations: int = 100, backfit_tolerance: float = 0.1, backfit_warm_start: bool = True, nuisance_num_trees: int | None = None, max_memory_gb: float | None = None, memory_reserve: float | None = None, workdir=None, keep_workdir: bool = False, n_threads: int | None = None, seed: int = 0, profile: bool = False, verbose: bool = False, ) -> CausalForestResult | Profile: """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_size` is 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, fixef_rm, max_iterations, backfit_tolerance, 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; use ``nuisance="linear"`` for a fast alternative. `fixef_rm` is as in `regression_forest`. `max_iterations` (default 100) and `backfit_tolerance` (default 0.1, a fraction of the effects' standard error) stop the backfitting; see `regression_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_reserve` and what the process already holds; a smaller budget means more passes over the data. memory_reserve : float, optional The share of `max_memory_gb` kept 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. """ return _fit_causal(None, **locals())
def _fit_causal( instrument, fml, data, *, cluster: str | None = None, weights: str | None = None, num_trees: int = 2000, min_node_size: int = 5, features_per_split: int | None = None, min_treatment_variation: float = 0.05, sample_fraction: float = 0.5, honesty_fraction: float = 0.5, variance_group_size: int = 2, max_bins: int = 256, nuisance: str = "forest", fixed_effects: str = "backfit", fixef_rm: str = "none", max_iterations: int = 100, backfit_tolerance: float = 0.1, backfit_warm_start: bool = True, nuisance_num_trees: int | None = None, max_memory_gb: float | None = None, memory_reserve: float | None = None, workdir=None, keep_workdir: bool = False, n_threads: int | None = None, seed: int = 0, profile: bool = False, verbose: bool = False, ) -> CausalForestResult | Profile: from stream_limits import thread_scope f = parse_forest_formula(fml, causal=True) iv = instrument is not None if iv and instrument in (f.outcome, f.treatment, *f.features): raise ValueError( f"the instrument {instrument!r} is also the outcome, the treatment or a feature" ) if nuisance not in ("forest", "linear"): raise ValueError(f"nuisance must be 'forest' or 'linear', not {nuisance!r}") mode = _check_fixed_effects(fixed_effects, f.fixed_effects, ("backfit", "outcome_within")) if fixed_effects == "group_means" or ( f.fixed_effects and fixed_effects not in ("backfit", "outcome_within") ): raise ValueError( "fixed_effects='group_means' is for regression forests; for a causal forest use " "'backfit' or 'outcome_within', or nuisance='linear' for the fast alternative" ) group = variance_group_size nuis_trees = _group_trees(nuisance_num_trees or max(200, num_trees // 4), 1) options = dict( num_trees=num_trees, min_node_size=min_node_size, features_per_split=features_per_split, min_treatment_variation=min_treatment_variation, sample_fraction=sample_fraction, honesty_fraction=honesty_fraction, variance_group_size=variance_group_size, max_bins=max_bins, max_memory_gb=max_memory_gb, memory_reserve=memory_reserve, cluster=cluster, weights=weights, seed=seed, nuisance=nuisance, fixed_effects=mode, ) if profile: return _profile_causal(f, data, locals(), options, nuis_trees, instrument) engine = _make_engine( "instrumental" if iv else "causal", options, workdir, keep_workdir, verbose ) log = engine._log info = {} with thread_scope(n_threads): t0 = time.perf_counter() if nuisance == "linear": keep = [c for c in (cluster, weights) if c] # the residuals' files are read while the forest is binned, so the # hdfe-stream fit is held until then lf, hdfe_fit = residualize_hdfe( _positive_weights(data, weights), f.outcome, f.treatment, f.features, f.fe, workdir=workdir, keep=keep, **({"weights": weights} if weights else {}), **({} if verbose else {"verbose": False}), **({"instrument": instrument} if iv else {}), ) centering_s = time.perf_counter() - t0 engine.fit( lf, f.features, "Y_res", "W_res", cluster=cluster, row_id="row_id", weights=weights, instrument="Z_res" if iv else None, ) del hdfe_fit else: cols = [f.outcome, f.treatment, *f.features, *_fe.fe_columns(f.fixed_effects)] cols += [instrument] if iv else [] lf = _clean_rows(data, [*cols, *([cluster] if cluster else [])], weights) engine.build_store( lf, f.features, f.outcome, f.treatment, cluster, "row_id", weights, instrument ) store = engine.store effects = None if mode: effects = _fe.GroupEffects( f.fixed_effects, lf, store, engine.workdir / "fe", engine.chunk_rows, verbose, fixef_rm=fixef_rm, ) res = {} for which in ("y", "w", *(("z",) if iv else ())): bf = _fe.backfit( store=store, which=which, effects=effects, make_engine=_round_engine(engine, nuis_trees), workdir=engine.workdir / f"nuisance_{which}", tolerance=backfit_tolerance, warm_start=backfit_warm_start, max_iterations=max_iterations, chunk_rows=engine.chunk_rows, iterate=mode == "backfit", log=log, ) res[which] = _residual( bf, store, engine.workdir / f"residual_{which}.npy", engine.chunk_rows ) info[which] = _diagnostics(bf) _set_treatment_and_outcome(store, res["w"], res["y"], engine.chunk_rows, res.get("z")) centering_s = time.perf_counter() - t0 - engine.timings["bin"] engine.fit_trees() result = (InstrumentalForestResult if iv else CausalForestResult)( fml, f, engine, centering_s, options ) if iv: result.instrument = instrument result.weights = weights result.fixed_effects_method = mode if nuisance == "forest" else None result.nuisance = nuisance result.backfit = info or None return result
[docs] def instrumental_forest( fml: str, data, *, instrument: str, cluster: str | None = None, weights: str | None = None, num_trees: int = 2000, min_node_size: int = 5, features_per_split: int | None = None, min_treatment_variation: float = 0.05, sample_fraction: float = 0.5, honesty_fraction: float = 0.5, variance_group_size: int = 2, max_bins: int = 256, nuisance: str = "forest", fixed_effects: str = "backfit", fixef_rm: str = "none", max_iterations: int = 100, backfit_tolerance: float = 0.1, backfit_warm_start: bool = True, nuisance_num_trees: int | None = None, max_memory_gb: float | None = None, memory_reserve: float | None = None, workdir=None, keep_workdir: bool = False, n_threads: int | None = None, seed: int = 0, profile: bool = False, verbose: bool = False, ) -> InstrumentalForestResult | Profile: """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 in `causal_forest`; with ``nuisance="forest"`` that is three out-of-bag forests. Parameters ---------- fml : str ``"y ~ w | x1 + x2"`` or ``"y ~ w | x1 + x2 | worker + firm"``, as for `causal_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_variation` is 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_test`` is not available. """ return _fit_causal(instrument, **{k: v for k, v in locals().items() if k != "instrument"})
[docs] def regression_forest( fml: str, data, *, cluster: str | None = None, weights: str | None = None, num_trees: int = 2000, min_node_size: int = 5, features_per_split: int | None = None, min_child_fraction: float = 0.05, sample_fraction: float = 0.5, honesty_fraction: float = 0.5, variance_group_size: int = 2, max_bins: int = 256, fixed_effects: str = "backfit", fixef_rm: str = "none", max_iterations: int = 100, backfit_tolerance: float = 0.1, backfit_warm_start: bool = True, backfit_num_trees: int | None = None, max_memory_gb: float | None = None, memory_reserve: float | None = None, workdir=None, keep_workdir: bool = False, n_threads: int | None = None, seed: int = 0, profile: bool = False, verbose: bool = False, ) -> RegressionForestResult | Profile: """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, honesty_fraction, variance_group_size, 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 estimates ``g``, so predictions are net of the group effects. ``"backfit"`` alternates a forest and the group effects: a forest is fitted to ``y`` less the current effects, its out-of-bag predictions are subtracted from ``y``, and the effects are re-estimated from what is left (hdfe-stream), until they change by less than `backfit_tolerance` times their own standard error or `max_iterations` rounds 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 in `between_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 (the `cluster`; 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; ``False`` grows 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 has `num_trees`. max_memory_gb, memory_reserve, workdir, keep_workdir, n_threads, seed, profile, verbose As in `causal_forest`. Returns ------- RegressionForestResult or Profile Notes ----- Rows with a missing or infinite value in any column used are dropped. """ f = parse_forest_formula(fml, causal=False) options = dict( num_trees=num_trees, min_node_size=min_node_size, features_per_split=features_per_split, min_child_fraction=min_child_fraction, sample_fraction=sample_fraction, honesty_fraction=honesty_fraction, variance_group_size=variance_group_size, max_bins=max_bins, max_memory_gb=max_memory_gb, memory_reserve=memory_reserve, cluster=cluster, weights=weights, seed=seed, ) return _outcome_forest( fml, f, data, options, kind="regression", engine_over={"node_size_rule": "split"}, result_cls=RegressionForestResult, fixed_effects=fixed_effects, fixef_rm=fixef_rm, max_iterations=max_iterations, backfit_tolerance=backfit_tolerance, backfit_warm_start=backfit_warm_start, backfit_num_trees=backfit_num_trees, workdir=workdir, keep_workdir=keep_workdir, n_threads=n_threads, profile=profile, verbose=verbose, )
[docs] def quantile_forest( fml: str, data, *, quantiles=(0.1, 0.5, 0.9), cluster: str | None = None, weights: str | None = None, num_trees: int = 2000, min_node_size: int = 5, features_per_split: int | None = None, min_child_fraction: float = 0.05, sample_fraction: float = 0.5, honesty_fraction: float = 0.5, max_bins: int = 256, max_memory_gb: float | None = None, memory_reserve: float | None = None, workdir=None, keep_workdir: bool = False, n_threads: int | None = None, seed: int = 0, verbose: bool = False, ) -> QuantileForestResult: """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. `predict` can 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, keep_workdir, n_threads, seed, 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. """ from stream_limits import thread_scope f = parse_forest_formula(fml, causal=False) if f.fixed_effects: raise ValueError( "fixed effects are not available for quantile forests yet: the group effects of " "a mean model do not shift every quantile alike. Remove them from the data first, " "or put the groups' dummies or group means in the features." ) options = dict( num_trees=num_trees, min_node_size=min_node_size, features_per_split=features_per_split, min_child_fraction=min_child_fraction, sample_fraction=sample_fraction, honesty_fraction=honesty_fraction, variance_group_size=1, max_bins=max_bins, max_memory_gb=max_memory_gb, memory_reserve=memory_reserve, cluster=cluster, weights=weights, seed=seed, quantiles=[float(q) for q in np.atleast_1d(quantiles)], fixed_effects=None, ) cols = [f.outcome, *f.features] cols += [cluster] if cluster else [] cols += [weights] if weights else [] lf = _clean_rows(data, cols, weights) engine = _make_engine( "quantile", options, workdir, keep_workdir, verbose, node_size_rule="split", quantiles=options["quantiles"], ) # fmt: skip with thread_scope(n_threads): engine.build_store(lf, list(f.features), f.outcome, None, cluster, "row_id", weights) engine.fit_trees() result = QuantileForestResult(fml, f, engine, 0.0, options) result.weights = weights return result
[docs] def random_forest( fml: str, data, *, task: str = "auto", cluster: str | None = None, weights: str | None = None, num_trees: int = 500, min_node_size: int | None = None, node_size_rule: str = "split", features_per_split: int | None = None, min_child_fraction: float = 0.0, max_depth: int | None = None, criterion: str = "gini", sample_fraction: float | None = None, replace: bool = True, honesty: bool = False, honesty_fraction: float = 0.5, variance_group_size: int = 1, max_bins: int = 256, fixed_effects: str = "backfit", fixef_rm: str = "none", max_iterations: int = 100, backfit_tolerance: float = 0.1, backfit_warm_start: bool = True, backfit_num_trees: int | None = None, max_memory_gb: float | None = None, memory_reserve: float | None = None, workdir=None, keep_workdir: bool = False, n_threads: int | None = None, seed: int = 0, profile: bool = False, verbose: bool = False, ) -> RandomForestResult | ClassificationForestResult | Profile: """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_rule` says how it is enforced. Default 5 for regression, 1 for classification. node_size_rule : {"split", "leaf"}, default "split" ``"split"``: a node with at most `min_node_size` rows is not split, and the children of a split may be of any size, so leaves can be smaller than `min_node_size` (the rule of ranger, R's randomForest and grf). ``"leaf"``: a node with fewer than twice `min_node_size` rows is not split and every child has at least that many (the rule of scikit-learn's ``min_samples_leaf`` and rpart's ``minbucket``). features_per_split : int, optional Features tried at each split, chosen at random without replacement. Default ``ceil(sqrt(p))`` for classification and ``ceil(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_fraction` implies (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 probability ``exp(-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_fraction` of 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 needs `sample_fraction` of at most 0.5. max_bins : int, default 256 Bins per feature (at most 256). fixed_effects, fixef_rm, max_iterations, backfit_tolerance, backfit_warm_start, backfit_num_trees For a numeric outcome with fixed effects in the formula: see `regression_forest`. Not available for classification. max_memory_gb, memory_reserve, workdir, keep_workdir, n_threads, seed, profile, verbose As in `causal_forest`. Returns ------- RandomForestResult or ClassificationForestResult or Profile """ f = parse_forest_formula(fml, causal=False) kind = _task_kind(data, f.outcome, task) if min_node_size is None: min_node_size = 1 if kind == "classification" else 5 if sample_fraction is None: sample_fraction = 1.0 if replace else 0.632 options = dict( num_trees=num_trees, min_node_size=min_node_size, features_per_split=features_per_split, min_child_fraction=min_child_fraction, sample_fraction=sample_fraction, honesty_fraction=honesty_fraction, variance_group_size=variance_group_size, max_bins=max_bins, max_memory_gb=max_memory_gb, memory_reserve=memory_reserve, cluster=cluster, weights=weights, seed=seed, ) over = dict( replace=replace, honesty=honesty, max_depth=max_depth, criterion=criterion, node_size_rule=node_size_rule, poisson_features=False, mtry_rule="sqrt" if kind == "classification" else "third", ) return _outcome_forest( fml, f, data, options, kind=kind, engine_over=over, result_cls=ClassificationForestResult if kind == "classification" else RandomForestResult, fixed_effects=fixed_effects, fixef_rm=fixef_rm, max_iterations=max_iterations, backfit_tolerance=backfit_tolerance, backfit_warm_start=backfit_warm_start, backfit_num_trees=backfit_num_trees, workdir=workdir, keep_workdir=keep_workdir, n_threads=n_threads, profile=profile, verbose=verbose, )
[docs] def decision_tree( fml: str, data, *, task: str = "auto", cluster: str | None = None, weights: str | None = None, max_depth: int = 6, min_node_size: int = 5, node_size_rule: str = "leaf", min_child_fraction: float = 0.0, min_impurity_decrease: float = 0.0, criterion: str = "gini", sample_fraction: float = 1.0, replace: bool = False, honesty: bool = False, honesty_fraction: float = 0.5, max_bins: int = 256, fixed_effects: str = "backfit", fixef_rm: str = "none", max_iterations: int = 100, backfit_tolerance: float = 0.1, backfit_warm_start: bool = True, max_memory_gb: float | None = None, memory_reserve: float | None = None, workdir=None, keep_workdir: bool = False, n_threads: int | None = None, seed: int = 0, profile: bool = False, verbose: bool = False, ) -> DecisionTreeResult | ClassificationTreeResult | Profile: """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_depth` limits 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_rule` says how it is enforced. node_size_rule : {"leaf", "split"}, default "leaf" ``"leaf"``: a node with fewer than twice `min_node_size` rows is not split and every child has at least that many (scikit-learn's ``min_samples_leaf``, rpart's ``minbucket``). ``"split"``: a node with at most `min_node_size` rows 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_fraction` of 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, fixef_rm, max_iterations, backfit_tolerance, 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, memory_reserve, workdir, keep_workdir, n_threads, seed, profile, verbose As in `causal_forest`. Returns ------- DecisionTreeResult or ClassificationTreeResult or Profile """ f = parse_forest_formula(fml, causal=False) kind = _task_kind(data, f.outcome, task) if max_depth < 1 or max_depth > 24: raise ValueError("max_depth must be between 1 and 24") options = dict( num_trees=1, min_node_size=min_node_size, features_per_split=None, min_child_fraction=min_child_fraction, sample_fraction=sample_fraction, honesty_fraction=honesty_fraction, variance_group_size=1, max_bins=max_bins, max_memory_gb=max_memory_gb, memory_reserve=memory_reserve, cluster=cluster, weights=weights, seed=seed, ) over = dict( single_tree=True, replace=replace, honesty=honesty, max_depth=max_depth, criterion=criterion, node_size_rule=node_size_rule, min_impurity_decrease=min_impurity_decrease, poisson_features=False, ) return _outcome_forest( fml, f, data, options, kind=kind, engine_over=over, result_cls=ClassificationTreeResult if kind == "classification" else DecisionTreeResult, fixed_effects=fixed_effects, fixef_rm=fixef_rm, max_iterations=max_iterations, backfit_tolerance=backfit_tolerance, backfit_warm_start=backfit_warm_start, backfit_num_trees=1, workdir=workdir, keep_workdir=keep_workdir, n_threads=n_threads, profile=profile, verbose=verbose, )
def _task_kind(data, outcome, task): if task not in ("auto", "regression", "classification"): raise ValueError(f"task must be 'auto', 'regression' or 'classification', not {task!r}") if task != "auto": return task schema = as_lazy(data).collect_schema() if outcome not in schema: raise ValueError(f"columns not in the data: {[outcome]}") dtype = schema[outcome] if dtype.is_numeric(): return "regression" return "classification" def _encode_classes(lf, outcome): """`lf` with the outcome as class codes 0..K-1 (floats, in the order of the sorted labels), and the labels.""" dtype = lf.collect_schema()[outcome] if dtype == pl.Categorical or isinstance(dtype, pl.Enum): lf = lf.with_columns(pl.col(outcome).cast(pl.String)) classes = lf.select(pl.col(outcome).unique().sort()).collect(engine="streaming")[outcome] classes = classes.to_list() if len(classes) < 2: raise ValueError(f"the outcome {outcome!r} has one class") if len(classes) > _MAX_CLASSES: raise ValueError( f"the outcome {outcome!r} has {len(classes):,} distinct values: more than " f"{_MAX_CLASSES} classes. If it is a continuous outcome, use task='regression'." ) lf = lf.with_columns( pl.col(outcome).replace_strict( classes, [float(i) for i in range(len(classes))], return_dtype=pl.Float64 ) ) return lf, classes _MAX_CLASSES = 100 def _outcome_forest( fml, f, data, options, *, kind, engine_over, result_cls, fixed_effects, fixef_rm, max_iterations, backfit_tolerance, backfit_warm_start, backfit_num_trees, workdir, keep_workdir, n_threads, profile, verbose, ): """A regression or classification forest of the outcome on the features, with fixed effects removed (regression only).""" from stream_limits import thread_scope num_trees = options["num_trees"] cluster = options["cluster"] mode = _check_fixed_effects(fixed_effects, f.fixed_effects, _fe.FIXED_EFFECTS) if kind == "classification" and f.fixed_effects: raise ValueError( "fixed effects are not available for classification: an additive group effect " "has no meaning for class labels. Use a regression forest on a numeric outcome, " "or put the groups' dummies or group means in the features." ) bf_trees = backfit_num_trees or max(100, num_trees // 4) weights = options["weights"] cols = [f.outcome, *f.features, *_fe.fe_columns(f.fixed_effects)] cols += [cluster] if cluster else [] cols += [weights] if weights else [] lf = _clean_rows(data, cols, weights) classes = None if kind == "classification": lf, classes = _encode_classes(lf, f.outcome) engine_over = {**engine_over, "n_classes": len(classes)} options = {**options, "fixed_effects": mode} features = list(f.features) tables = None if mode == "group_means": lf, cluster = _group_cluster(lf, f.fixed_effects, cluster) options["cluster"] = cluster tables = _fe.group_mean_tables(lf, f.features, f.fixed_effects, weights) lf = _fe.add_group_means(lf, tables, f.fixed_effects) features += _fe.mean_feature_names(f.features, f.fixed_effects) if profile: return _profile_regression(f, lf, cols, options, mode, bf_trees, n_threads) engine = _make_engine(kind, options, workdir, keep_workdir, verbose, **engine_over) info = None shares = None effects_path = None group_tables = None with thread_scope(n_threads): engine.build_store(lf, features, f.outcome, None, cluster, "row_id", weights) store = engine.store centering_s = 0.0 if mode in ("backfit", "outcome_within"): tc = time.perf_counter() effects = _fe.GroupEffects( f.fixed_effects, lf, store, engine.workdir / "fe", engine.chunk_rows, verbose, fixef_rm=fixef_rm, ) if mode == "backfit": bf = _fe.backfit( store=store, which="y", effects=effects, make_engine=_round_engine(engine, bf_trees), workdir=engine.workdir / "backfit", tolerance=backfit_tolerance, warm_start=backfit_warm_start, max_iterations=max_iterations, chunk_rows=engine.chunk_rows, log=engine._log, ) y0, a = bf.y0, bf.effects info = _diagnostics(bf) else: shares = _fe.between_group_shares( lf.select( *features, *_fe.fe_columns(f.fixed_effects), *([weights] if weights else []) ), features, f.fixed_effects, engine.workdir / "shares", verbose, weights, ) worst = max(shares, key=shares.get) if shares[worst] > 0.10: warnings.warn( f"{shares[worst]:.0%} of the variance of {worst!r} lies between groups: " "with features that related to the groups, outcome_within estimates the " "wrong function. Use fixed_effects='backfit'.", _fe.FixedEffectsWarning, stacklevel=3, ) y0 = _fe.column(store, "y", engine.workdir / "y0.npy", engine.chunk_rows) a = engine.workdir / "a.npy" effects.fitted(y0, a) r = engine.workdir / "r.npy" _fe.write_difference(y0, a, r, store.n, engine.chunk_rows) engine.outcome_file = r centering_s = time.perf_counter() - tc effects_path = a group_tables = effects.tables() engine.fit_trees() result = result_cls(fml, f, engine, centering_s, options) result.weights = weights result.fixed_effects_method = mode result.backfit = info result.between_group_share = shares result._terms = list(f.fixed_effects) if mode == "group_means" else [] result._tables = tables result._effects_path = effects_path if group_tables is not None: result._effect_tables, result._intercept = group_tables result.classes = classes return result def _group_cluster(lf, terms, cluster): """The sampling unit when fixed-effect group means are features: the fixed effect itself, unless the user gives another.""" if cluster: return lf, cluster if len(terms) != 1: raise ValueError( "with several fixed effects, fixed_effects='group_means' needs cluster=: the " "rows should be sampled together by the groups the means come from" ) cols = [c.strip() for c in terms[0].split("^")] if len(cols) == 1: return lf, cols[0] return lf.with_columns(pl.struct(cols).hash().alias("__group")), "__group" def _profile_pieces( lf, cols, outcome, terms, n_rounds_vectors, o, p, n_threads, trees, row_extra=0 ): from hdfe_stream.core.profile import Component, scan_source from stream_limits import detect_cpus scan = scan_source(lf, present=[pl.col(c) for c in cols]) group = o["variance_group_size"] forest = forest_profile( n=scan.n_rows, p=p, num_trees=_group_trees(trees, group), group=group, o=o, chunk_rows=500_000, max_memory_gb=o["max_memory_gb"], memory_reserve=o["memory_reserve"], threads=n_threads or detect_cpus(), row_extra=row_extra, ) comps = list(forest.components) if n_rounds_vectors: n = scan.n_rows comps += [ Component( "out-of-bag predictions of a round", 16 * n, 16 * n, phases=("grow",), formula=f"{n:,} rows x 16 B", ), Component( "outcome, effects and fitted values (files)", 32 * n * n_rounds_vectors, 32 * n * n_rounds_vectors, where="disk", formula=f"{n:,} rows x 32 B x {n_rounds_vectors}", ), ] if terms: from hdfe_stream import feols_stream h = feols_stream(f"{outcome} ~ 1 | {' + '.join(terms)}", lf, profile=True) return dataclasses.replace( h, components=[*h.components, *comps], warnings=[*h.warnings, *forest.warnings], notes={**h.notes, **forest.notes}, scan=scan, ) return dataclasses.replace(forest, components=comps, scan=scan) def _profile_regression(f, lf, cols, o, mode, bf_trees, n_threads): p = len(f.features) * (1 + (len(f.fixed_effects) if mode == "group_means" else 0)) prof = _profile_pieces( lf, cols, f.outcome, f.fixed_effects if mode in ("backfit", "outcome_within") else [], 1 if mode in ("backfit", "outcome_within") else 0, o, p, n_threads, o["num_trees"], ) prof.model = f"regression forest {f.outcome} ~ {' + '.join(f.features)}" + ( f" | {' + '.join(f.fixed_effects)} ({mode})" if f.fixed_effects else "" ) return prof def _profile_causal(f, data, args, o, nuis_trees, instrument=None): if o["nuisance"] == "forest": cols = [f.outcome, f.treatment, *f.features, *_fe.fe_columns(f.fixed_effects)] cols += [instrument] if instrument else [] cols += [args["cluster"]] if args["cluster"] else [] cols += [args["weights"]] if args["weights"] else [] lf = _clean_rows(data, cols, args["weights"]) terms = f.fixed_effects if o["fixed_effects"] else [] prof = _profile_pieces( lf, cols, f.outcome, terms, 4 if instrument else 3, o, len(f.features), args["n_threads"], o["num_trees"], row_extra=8 if instrument else 0, ) prof.model = ( f"{'instrumental' if instrument else 'causal'} forest {f.outcome} ~ {f.treatment} " f"| {' + '.join(f.features)}" ) return prof return _profile_linear(f, data, args, instrument) def _profile_linear(f, data, args, instrument=None): """The profile of the linear centering: hdfe-stream's, then the forest's binning and growing, as phases of one fit.""" from hdfe_stream import feols_stream from stream_limits import detect_cpus centering = feols_stream( centering_formula(f.outcome, f.treatment, f.features, f.fe, instrument=instrument), data, workdir=args["workdir"], profile=True, **({"max_memory_gb": args["max_memory_gb"]} if args["max_memory_gb"] else {}), ) group = args["variance_group_size"] forest = forest_profile( n=centering.scan.n_rows, p=len(f.features), num_trees=_group_trees(args["num_trees"], group), group=group, o=args, chunk_rows=500_000, max_memory_gb=args["max_memory_gb"], memory_reserve=args["memory_reserve"], threads=args["n_threads"] or detect_cpus(), row_extra=8 if instrument else 0, ) # the centering's components keep their phases, and its result files stay # until the forest is fitted; the forest's components follow in "bin" and "grow" return dataclasses.replace( centering, model=f"{'instrumental' if instrument else 'causal'} forest {f.outcome} ~ {f.treatment} " f"| {' + '.join(f.features)}", components=[*centering.components, *forest.components], warnings=[*centering.warnings, *forest.warnings], notes={**centering.notes, **forest.notes}, ) def _clean_rows(data, cols, weights=None): """The rows of `data` with every column of `cols` present and finite (and the weights, if any, positive), numbered by their position in `data` (``row_id``).""" cols = list(dict.fromkeys([*cols, *([weights] if weights else [])])) lf = _positive_weights(data, weights) schema = lf.collect_schema() missing = [c for c in cols if c not in schema] if missing: raise ValueError(f"columns not in the data: {missing}") checks = [] for c in cols: checks.append(pl.col(c).is_not_null()) if schema[c].is_float(): checks.append(pl.col(c).is_finite()) return lf.with_row_index("row_id").filter(pl.all_horizontal(checks)).select("row_id", *cols) def _positive_weights(data, weights): """`data` as a lazy frame, without the rows whose weight is zero. A negative weight is an error; missing weights are dropped with the other missing values.""" lf = as_lazy(data) if not weights: return lf schema = lf.collect_schema() if weights not in schema: raise ValueError(f"columns not in the data: {[weights]}") if not schema[weights].is_numeric(): raise ValueError(f"the weights {weights!r} are not numeric") if lf.select((pl.col(weights) < 0).any()).collect(engine="streaming").item(): raise ValueError(f"negative weights in {weights!r}") return lf.filter(pl.col(weights).is_null() | (pl.col(weights) > 0))