Source code for forest_stream.results

"""The results of forest fits."""

from __future__ import annotations

import warnings
from dataclasses import dataclass
from pathlib import Path

import numpy as np
import polars as pl
from hdfe_stream.core.results_base import RegressionResult
from hdfe_stream.core.utils import as_lazy
from stream_limits import thread_scope

from ._fe import add_group_means, fe_columns
from ._inference import ols, parse_vcov
from .forest import ForestEngine, load_batch


def _weighted_groups(x, values, weights, groups):
    """``(mean x, mean value, standard error of the mean)`` for `groups` groups of rows
    of equal weight, ordered by `x`; rows with a missing x or value are left out."""
    ok = np.isfinite(x) & np.isfinite(values)
    x, v, w = x[ok], values[ok], weights[ok]
    order = np.argsort(x, kind="stable")
    x, v, w = x[order], v[order], w[order]
    share = np.cumsum(w) / w.sum()
    which = np.minimum(np.floor((share - 1e-12) * groups).astype(int), groups - 1)
    out = []
    for g in range(groups):
        m = which == g
        if not m.any():
            continue
        wg = w[m]
        mean = np.average(v[m], weights=wg)
        var = np.average((v[m] - mean) ** 2, weights=wg)
        n_eff = wg.sum() ** 2 / (wg**2).sum()
        out.append((np.average(x[m], weights=wg), mean, np.sqrt(var / n_eff)))
    return np.array(out).T


class ForestResult:
    """A fitted forest.

    The trees and the binned training data live in a run directory on disk
    (`workdir`), which the result owns: it is deleted when the result is
    garbage-collected or `close()` is called, unless the fit used
    ``keep_workdir=True``. `predict` and everything else computed from the
    forest needs it.

    Attributes
    ----------
    fml : str
        The formula.
    outcome : str
        The outcome column.
    features : list of str
        The feature columns, in the order the forest was trained on.
    n_obs : int
        Rows the forest was fitted on (rows with a missing value in a column
        used are dropped before).
    num_trees : int
        Trees grown (rounded up to a multiple of `variance_group_size`).
    workdir : pathlib.Path
        The run directory.
    timings : dict
        Seconds spent binning, in passes over the data, growing trees, and in
        total.
    """

    _title = "Forest"
    _estimate_name = "prediction"
    weights = None  # the column of sample weights, if any
    fixed_effects_method = None
    backfit = None
    between_group_share = None
    _terms: list = []
    _tables = None
    _effects_path = None
    _effect_tables = None  # {term: table of the group effects}, with fixed effects removed
    _intercept = 0.0

    def __init__(self, fml, formula, engine, centering_s, options):
        self.fml = fml
        self.outcome = formula.outcome
        self.features = list(formula.features)
        self._engine = engine
        self.n_obs = engine.store.n
        self.num_trees = engine.num_trees
        self.options = options
        self.timings = {**engine.timings, "centering": centering_s}
        self.n_passes = engine.n_passes

    @property
    def workdir(self):
        return self._engine.workdir

    def predict(
        self,
        data,
        variance: bool | None = None,
        n_threads: int | None = None,
        *,
        include_fixed_effects: bool = False,
        new_groups: str = "error",
        keep: list[str] | None = None,
        output=None,
        batch_rows: int | None = None,
    ):
        """Predictions at the rows of `data`, read and predicted in batches, so
        that only a batch's features, and the predictions, are in memory (and
        with `output`, not even those).

        Parameters
        ----------
        data : str, polars.DataFrame or polars.LazyFrame
            A Parquet path or glob, or a frame, with the feature columns.
        variance : bool, optional
            Also return each estimate's variance (little-bags, with a
            debiasing correction). Default: when ``variance_group_size`` is
            above 1, which it needs to be.
        n_threads : int, optional
            Threads for the compiled passes. Default: all that the job may use.
        include_fixed_effects : bool, default False
            For a forest fitted with fixed effects (``"backfit"`` or
            ``"outcome_within"``), add each row's group effects to its
            prediction, which is otherwise net of them: ``prediction`` is then
            the forest's estimate plus the effects, and ``fixed_effect`` is the
            effects' sum. The data need the fixed-effect columns. The variance is
            the forest's, and does not allow for the error in the effects.
        new_groups : {"error", "nan", "zero"}, default "error"
            With `include_fixed_effects`, what to do with a row whose group was
            not in the data the forest was fitted on: raise an error, give it a
            missing prediction, or give it a zero effect.
        keep : list of str, optional
            Columns of `data` to carry into the output, in front of the
            predictions (an identifier, say).
        output : str or path, optional
            Write the predictions to this Parquet file, batch by batch, and
            return its path, instead of returning them.
        batch_rows : int, optional
            Rows per batch. Default 250,000.

        Returns
        -------
        polars.DataFrame or pathlib.Path
            One row per row of `data`: any `keep` columns, the estimate (``tau``
            for a causal forest, ``prediction`` for a regression forest, or
            ``class`` and ``prob_<label>`` for a classification forest), with
            `variance` its ``variance`` (``variance_<label>``), and with
            `include_fixed_effects` ``fixed_effect``. With `output`, the path.
        """
        variance = self._wants_variance(variance)
        if new_groups not in ("error", "nan", "zero"):
            raise ValueError(f"new_groups must be 'error', 'nan' or 'zero', not {new_groups!r}")
        if include_fixed_effects and self._effect_tables is None:
            raise ValueError(
                "include_fixed_effects needs a forest fitted with fixed effects and "
                "fixed_effects='backfit' or 'outcome_within'"
            )
        keep = list(keep or [])
        lf = as_lazy(data)
        schema = lf.collect_schema()
        need = [*self.features, *keep]
        if self._tables is not None:
            need += fe_columns(self._terms)
        if include_fixed_effects:
            need += fe_columns(list(self._effect_tables))
        need = list(dict.fromkeys(need))
        missing = [c for c in need if c not in schema]
        if missing:
            raise ValueError(f"columns not in the data: {missing}")
        rows = batch_rows or 250_000
        batches = lf.select(need).collect_batches(chunk_size=rows)
        frames = (
            self._predict_batch(df, variance, include_fixed_effects, new_groups, keep)
            for df in batches
        )
        with thread_scope(n_threads):
            if output is None:
                parts = list(frames)
                return pl.concat(parts) if parts else pl.DataFrame()
            import pyarrow.parquet as pq

            writer = None
            try:
                for part in frames:
                    table = part.to_arrow()
                    if writer is None:
                        writer = pq.ParquetWriter(output, table.schema)
                    writer.write_table(table)
            finally:
                if writer is not None:
                    writer.close()
            return Path(output)

    def _predict_batch(self, df, variance, include_fixed_effects, new_groups, keep):
        x = self._feature_matrix(df)
        if variance:
            est, var = self._engine.predict(x, estimate_variance=True)
            frame = self._frame(est, var)
        else:
            frame = self._frame(self._engine.predict(x, estimate_variance=False), None)
        if include_fixed_effects:
            effect = self._effects_of(df, new_groups)
            name = self._estimate_name
            frame = frame.with_columns((pl.col(name) + pl.Series(effect)).alias(name)).with_columns(
                fixed_effect=pl.Series(effect)
            )
        if keep:
            clash = [c for c in keep if c in frame.columns]
            if clash:
                raise ValueError(
                    f"keep: {clash} would have the name of a column of the predictions "
                    f"({frame.columns}); rename them in the data"
                )
            frame = pl.concat([df.select(keep), frame], how="horizontal")
        return frame

    def _effects_of(self, df, new_groups):
        """Each row's total group effect (and the intercept) from the fit."""
        total = np.full(df.height, self._intercept)
        for term, table in self._effect_tables.items():
            key = [c.strip() for c in term.split("^")]
            found = (
                df.select(key)
                .join(table, on=key, how="left", maintain_order="left")["effect"]
                .fill_null(np.nan)
                .to_numpy()
            )
            unknown = np.isnan(found)
            if unknown.any():
                if new_groups == "error":
                    raise ValueError(
                        f"{int(unknown.sum()):,} rows have a group in {term!r} that was not in "
                        "the data the forest was fitted on (new_groups='nan' or 'zero' allows it)"
                    )
                if new_groups == "zero":
                    found = np.where(unknown, 0.0, found)
            total = total + found
        return total

    def group_effects(self) -> dict:
        """The fixed effects of the fit, as ``{term: table}``: each table has
        the term's columns and the ``effect`` of each group (the effects of a row's
        groups, and `intercept`, add up to the part of its outcome that the fixed
        effects explain). For a forest fitted with ``fixed_effects="backfit"`` or
        ``"outcome_within"``."""
        if self._effect_tables is None:
            raise ValueError("this forest was not fitted with fixed effects removed")
        return dict(self._effect_tables)

    @property
    def intercept(self) -> float:
        """The constant that goes with the group effects (zero when the
        effects are normalized to hold the level, as hdfe-stream does)."""
        return float(self._intercept)

    def _wants_variance(self, variance):
        return self._engine.variance_group_size > 1 if variance is None else variance

    def _frame(self, est, var):
        """Estimates (and variances) as a frame."""
        out = {self._estimate_name: est}
        if var is not None:
            out["variance"] = var
        return pl.DataFrame(out)

    def _feature_matrix(self, df):
        """The engine's features for the rows of the frame `df`: the formula's,
        and, for ``fixed_effects="group_means"``, the groups' feature means from
        the fit, joined on."""
        if self._tables is None:
            x = df.select(self.features).to_numpy().astype(np.float64)
        else:
            cols = [*self.features, *fe_columns(self._terms)]
            names = self._engine.store.X
            joined = add_group_means(df.lazy().select(cols), self._tables, self._terms)
            x = joined.select(names).collect().to_numpy().astype(np.float64)
            if not np.isfinite(x).all():
                raise ValueError(
                    "some rows are in groups that were not in the data the forest was fitted on "
                    "(or have missing features): group means are not available for them"
                )
        if not np.isfinite(x).all():
            raise ValueError("missing or infinite values in the features")
        return x

    def oob_predictions(
        self, variance: bool | None = None, n_threads: int | None = None
    ) -> pl.DataFrame:
        """Out-of-bag predictions at the rows the forest was fitted on: each
        row's estimate uses only the trees whose subsample does not contain
        the row (or its cluster).

        Returns
        -------
        polars.DataFrame
            ``row_id`` (the row's position in the data, from 0), the estimate
            and, with `variance`, ``variance``.
        """
        variance = self._wants_variance(variance)
        with thread_scope(n_threads):
            out = self._engine.predict_oob(estimate_variance=variance)
        frame = self._frame(*out) if variance else self._frame(out, None)
        return frame.insert_column(0, pl.Series("row_id", self._engine.store.row_ids()))

    def variable_importance(self, decay_exponent: float = 2.0, max_depth: int = 4) -> pl.DataFrame:
        """How much the trees split on each feature: the share of splits on
        it at each depth, over the trees' first `max_depth` levels, averaged
        with weights proportional to ``depth ** -decay_exponent`` (so splits
        near the root count most). The importances sum to one.

        Returns
        -------
        polars.DataFrame
            ``feature`` and ``importance``, in the order of the formula (with the
            groups' feature means last, for ``fixed_effects="group_means"``).
        """
        counts = self._engine.split_frequencies(max_depth).astype(np.float64)
        share = counts / np.maximum(counts.sum(1, keepdims=True), 1.0)
        weight = np.arange(1, max_depth + 1, dtype=np.float64) ** -float(decay_exponent)
        weight /= weight.sum()
        return pl.DataFrame({"feature": self._engine.store.X, "importance": share.T @ weight})

    _plot_kinds = ("importance",)

    def plot(self, kind: str | None = None, *, ax=None, title: str | None = None, **options):
        """Draw a picture of the fit with matplotlib, which is not a dependency
        (``pip install forest-stream[plot]``).

        Parameters
        ----------
        kind : str, optional
            What to draw; the first of the kinds below is the default.
            ``"importance"``: bars of `variable_importance` (``top=`` limits the
            number). For regression and classification forests also
            ``"calibration"``: the mean outcome (or, for a class, its observed
            share) against the mean out-of-bag prediction, by groups of the
            prediction (``groups=``, default 10), with the diagonal. A decision
            tree's default is ``"tree"``: its nodes (``max_depth=`` shows fewer
            levels). A causal forest's are described in `CausalForestResult.plot`.
        ax : matplotlib.axes.Axes, optional
            Draw here instead of on a new figure.
        title : str, optional

        Returns
        -------
        matplotlib.figure.Figure
        """
        kind = kind or self._plot_kinds[0]
        if kind not in self._plot_kinds:
            raise ValueError(f"kind must be one of {self._plot_kinds}, not {kind!r}")
        return getattr(self, f"_plot_{kind}")(ax=ax, title=title, **options)

    def _plot_importance(self, *, ax, title, top=None, **options):
        from . import _plots

        if options:
            raise TypeError(f"unexpected options for kind='importance': {sorted(options)}")
        return _plots.importance(self.variable_importance(), ax=ax, title=title, top=top)

    def summary_text(self) -> str:
        """The fit's description as text."""
        t = self.timings
        return "\n".join(
            [
                self._title,
                f"  formula:        {self.fml}",
                f"  observations:   {self.n_obs:,}",
                f"  trees:          {self.num_trees:,}",
                f"  features:       {len(self.features)}",
                *self._extra_lines(),
                f"  passes:         {self.n_passes}",
                f"  seconds:        {t['fit'] + t['centering']:.1f} "
                f"(centering {t['centering']:.1f}, binning {t['bin']:.1f}, "
                f"growing {t['grow']:.1f})",
            ]
        )

    def _extra_lines(self) -> list[str]:
        return []

    def summary(self) -> None:
        """Print `summary_text`."""
        print(self.summary_text())

    def close(self) -> None:
        """Delete the run directory. The forest cannot predict afterwards."""
        self._engine.close()

    def __repr__(self) -> str:
        return f"<{type(self).__name__} {self.fml!r}: {self.num_trees} trees, {self.n_obs:,} rows>"


class _OutOfBagScore:
    """`oob_score` for forests of an outcome."""

    def oob_score(self, n_threads: int | None = None) -> dict:
        """How well the out-of-bag predictions predict the outcome the forest
        was fitted to (net of the fixed effects, when there are any).

        Returns
        -------
        dict
            For a regression forest ``rmse`` and ``r2`` (one minus the sum of
            squared errors over the outcome's variation); for a classification
            forest ``accuracy`` and ``log_loss``; weighted by the sample weights,
            if there are any. ``n`` is the rows scored (those with a tree out of
            bag).
        """
        e = self._engine
        with thread_scope(n_threads):
            pred = e.predict_oob(estimate_variance=False)
        y = np.concatenate([yy for _, _, yy, _, _, _ in e._chunks()])
        sw = e.store.weights()
        if e.kind == "classification":
            ok = ~np.isnan(pred).any(axis=1)
            truth, p, wt = y[ok].astype(np.int64), pred[ok], sw[ok]
            hit = float(np.average(p.argmax(axis=1) == truth, weights=wt))
            loss = float(
                -np.average(
                    np.log(np.clip(p[np.arange(truth.size), truth], 1e-15, 1.0)), weights=wt
                )
            )
            return {"accuracy": hit, "log_loss": loss, "n": int(ok.sum())}
        ok = np.isfinite(pred)
        err, wt = y[ok] - pred[ok], sw[ok]
        sse = float((wt * err**2).sum())
        sst = float((wt * (y[ok] - np.average(y[ok], weights=wt)) ** 2).sum())
        return {
            "rmse": float(np.sqrt(sse / wt.sum())),
            "r2": 1.0 - sse / sst if sst > 0 else float("nan"),
            "n": int(ok.sum()),
        }


def _calibration_plot(result, *, ax, title, groups=10):
    """The out-of-bag predictions against the outcome, by groups of the prediction."""
    from . import _plots

    e = result._engine
    pred = e.predict_oob(estimate_variance=False)
    y = np.concatenate([yy for _, _, yy, _, _, _ in e._chunks()])
    sw = e.store.weights()
    if e.kind == "classification":
        heavy = np.argsort([-sw[y == k].sum() for k in range(e.n_classes)])[:6]
        curves = []
        for k in sorted(heavy):
            gx, gy, gse = _weighted_groups(pred[:, k], (y == k).astype(float), sw, groups)
            curves.append((f"{result.classes[k]}", gx, gy, gse))
        labels = ("Mean out-of-bag probability", "Observed share")
    else:
        gx, gy, gse = _weighted_groups(pred, y, sw, groups)
        curves = [("", gx, gy, gse)]
        labels = ("Mean out-of-bag prediction", "Mean outcome")
    return _plots.reliability(curves, xlabel=labels[0], ylabel=labels[1], ax=ax, title=title)


[docs] class RegressionForestResult(_OutOfBagScore, ForestResult): """A fitted regression forest: honest trees whose leaves average the outcome. See `ForestResult`.""" _title = "Regression forest" _estimate_name = "prediction" _plot_kinds = ("importance", "calibration") def _plot_calibration(self, *, ax, title, groups=10): return _calibration_plot(self, ax=ax, title=title, groups=groups)
[docs] class RandomForestResult(RegressionForestResult): """A fitted random forest for a numeric outcome. See `ForestResult`.""" _title = "Random forest"
[docs] class ClassificationForestResult(_OutOfBagScore, ForestResult): """A fitted random forest for class labels. `predict` and `oob_predictions` return one probability column per class, ``prob_<label>``, the predicted ``class`` (the likeliest), and with `variance` a ``variance_<label>`` column per class. Attributes ---------- classes : list The class labels, in the order of the probability columns. """ _title = "Classification forest" classes = None _plot_kinds = ("importance", "calibration") def _plot_calibration(self, *, ax, title, groups=10): return _calibration_plot(self, ax=ax, title=title, groups=groups) def _extra_lines(self): return [f" classes: {len(self.classes)}"] def _frame(self, est, var): labels = [str(c) for c in self.classes] missing = np.isnan(est).any(axis=1) top = np.where(missing, 0, est.argmax(axis=1)) values = [self.classes[i] for i in top] out = {"class": pl.Series("class", values).set(pl.Series(missing), None)} for k, label in enumerate(labels): out[f"prob_{label}"] = est[:, k] if var is not None: for k, label in enumerate(labels): out[f"variance_{label}"] = var[:, k] return pl.DataFrame(out)
class _TreeTable: """The `tree` table of a decision tree, and its out-of-bag score.""" _plot_kinds = ("tree", "importance", "calibration") def _plot_tree(self, *, ax, title, max_depth=None): from . import _plots return _plots.tree( self.tree(), classification=self._engine.kind == "classification", max_depth=max_depth, ax=ax, title=title, ) def oob_score(self, n_threads: int | None = None) -> dict: """As for a forest, for the rows that are not in the tree's sample. A tree grown on all the rows (``sample_fraction=1`` without replacement) has none: score it on other data with `predict`.""" e = self._engine if e.rate >= 1 and not e.replace: raise ValueError( "every row is in the tree's sample, so none is out of bag: score the tree on " "other data, or grow it on a share of the rows (sample_fraction below 1)" ) return super().oob_score(n_threads) def tree(self) -> pl.DataFrame: """The fitted tree, one row per node, in depth-first order. A row sends an observation to ``left`` when its ``feature`` is below ``threshold``, and to ``right`` otherwise. Leaves have no feature. ``n`` is the number of rows (counted as many times as they are in the sample, when it is drawn with replacement) that estimate the node's value, and, with sample weights, ``weight`` their total weight: the estimation half of the sample with honesty, else the sample the tree was grown on. The value is ``prediction`` for a regression tree; for a classification tree ``class`` and one ``prob_<label>`` per class. Nodes that pruning removed (honesty) are not listed. """ e = self._engine with load_batch(e.batch_files[0]) as z: feat, thr = z["feat"], z["thr"] left, right, stats = z["left"], z["right"], z["stats"] root = int(z["root"][0]) classification = e.kind == "classification" rows = [] def visit(node, depth): row = {"depth": depth, "feature": None, "threshold": None, "left": None, "right": None} rows.append(row) if left[node] < 0: total = stats[node].copy() else: f, b = int(feat[node]), int(thr[node]) row["feature"], row["threshold"] = e.store.X[f], float(e.store.edges[f][b]) row["left"] = len(rows) lo = visit(int(left[node]), depth + 1) row["right"] = len(rows) hi = visit(int(right[node]), depth + 1) total = lo + hi row["_stats"] = total return total if root >= 0: visit(root, 1) labels = [str(c) for c in self.classes] if classification else [] out = {"node": list(range(len(rows)))} for key in ("depth", "feature", "threshold", "left", "right"): out[key] = [r[key] for r in rows] tot = [r["_stats"] for r in rows] if classification: k = len(labels) weight = [float(t[:k].sum()) for t in tot] out["n"] = [float(t[k]) for t in tot] if e.store.weighted: out["weight"] = weight out["class"] = [self.classes[int(t[:k].argmax())] for t in tot] for j, label in enumerate(labels): out[f"prob_{label}"] = [float(t[j] / m) for t, m in zip(tot, weight, strict=True)] else: out["n"] = [float(t[5]) for t in tot] if e.store.weighted: out["weight"] = [float(t[0]) for t in tot] out["prediction"] = [float(t[2] / t[0]) for t in tot] return pl.DataFrame(out)
[docs] class DecisionTreeResult(_TreeTable, RegressionForestResult): """A fitted decision tree for a numeric outcome. See `ForestResult`; there is no variance. `tree` lists its nodes.""" _title = "Decision tree"
[docs] class ClassificationTreeResult(_TreeTable, ClassificationForestResult): """A fitted decision tree for class labels. See `ClassificationForestResult`; there is no variance. `tree` lists its nodes.""" _title = "Classification tree"
[docs] @dataclass(kw_only=True) class TreatmentEffect(RegressionResult): """An average treatment effect with its standard error, from a causal forest's doubly robust scores. `beta` holds the one estimate and `vcov` its variance; `tidy`, `confint`, `summary`, `etable` and the rest of `RegressionResult` apply. Inference uses the normal distribution. Attributes ---------- estimand : str What the average is of. n_dropped : int Rows left out because no tree was out of bag for them. """ estimand: str = "average treatment effect" n_dropped: int = 0 _normal_inference = True def _summary_lines(self) -> list[str]: lines = [ f"estimand: {self.estimand}", f"vcov: {self.vcov_type}", f"obs: {self.n_obs:,}" + (f" ({self.n_dropped:,} not out of bag)" if self.n_dropped else ""), ] if self.n_clusters: lines.append("clusters: " + ", ".join(f"{k} {v:,}" for k, v in self.n_clusters.items())) return lines def _summary_fields(self) -> dict: out = super()._summary_fields() out.update(estimand=self.estimand, n_dropped=self.n_dropped) return out
[docs] @dataclass(kw_only=True) class LinearProjection(RegressionResult): """A least-squares fit on a causal forest's out-of-bag quantities: the best linear projection of the treatment effect on features, or the calibration test. `tidy`, `confint`, `summary`, `etable` and the rest of `RegressionResult` apply; p-values use the t distribution with `df_t` degrees of freedom. Attributes ---------- estimand : str What the regression is. n_dropped : int Rows left out because no tree was out of bag for them. """ estimand: str = "" n_dropped: int = 0 def _summary_lines(self) -> list[str]: lines = [ self.estimand, f"vcov: {self.vcov_type}", f"obs: {self.n_obs:,}" + (f" ({self.n_dropped:,} not out of bag)" if self.n_dropped else ""), ] if self.n_clusters: lines.append("clusters: " + ", ".join(f"{k} {v:,}" for k, v in self.n_clusters.items())) return lines def _summary_fields(self) -> dict: out = super()._summary_fields() out.update(estimand=self.estimand, n_dropped=self.n_dropped) return out
[docs] class CausalForestResult(ForestResult): """A fitted causal forest. See `ForestResult`. Besides `predict` and `oob_predictions`, it estimates the average treatment effect with `average_treatment_effect`. """ _title = "Causal forest" _estimate_name = "tau" _plot_kinds = ("effects", "heterogeneity", "importance", "calibration", "projection") _aux_target = "w2" # what the forest behind the scores' denominators predicts _ate_estimand = "average treatment effect"
[docs] def plot(self, kind: str | None = None, *, ax=None, title: str | None = None, **options): """Draw a picture of the effects with matplotlib, which is not a dependency (``pip install forest-stream[plot]``). Parameters ---------- kind : str, optional ``"effects"`` (the default): a histogram of the out-of-bag effect estimates, with the average effect and its interval. ``"heterogeneity"``: the mean estimate against a feature (``feature=``; default the most important one), in ``groups=`` (20) groups of rows of equal weight, and the average. The bars are 1.96 standard errors of each group's mean estimate (from the spread of the estimates in the group), not intervals for the group's true effect. ``"importance"``: bars of `variable_importance`. ``"calibration"``: the two coefficients of `calibration_test` with intervals, against their ideal value of one. ``"projection"``: the coefficients of `best_linear_projection` (``data=``, which it needs, and ``terms=``) with intervals. ax : matplotlib.axes.Axes, optional Draw here instead of on a new figure. title : str, optional Returns ------- matplotlib.figure.Figure """ return super().plot(kind, ax=ax, title=title, **options)
def _plot_effects(self, *, ax, title, bins=40): from . import _plots ate = self.average_treatment_effect() low, high = ate.confint().row(0)[1:] tau = np.asarray(self._scores()[:, 0]) return _plots.distribution( tau, center=ate.beta[0], low=low, high=high, label="Effect", ax=ax, title=title, bins=bins, ) def _plot_heterogeneity(self, *, ax, title, feature=None, groups=20): from . import _plots e = self._engine st = e.store if feature is None: vi = self.variable_importance() feature = vi["feature"][int(vi["importance"].arg_max())] if feature not in st.X: raise ValueError(f"feature must be one of {st.X}, not {feature!r}") j = st.X.index(feature) column = np.concatenate([b[:, j] for b, _, _, _ in st.chunks(e.chunk_rows)]).astype( np.int64 ) edges = st.edges[j] centers = np.concatenate([[edges[0]], (edges[:-1] + edges[1:]) / 2, [edges[-1]]]) x = centers[np.minimum(column, centers.size - 1)] tau = np.asarray(self._scores()[:, 0]) weights = st.weights() gx, gy, gse = _weighted_groups(x, tau, weights, groups) center = float(np.average(tau[np.isfinite(tau)], weights=weights[np.isfinite(tau)])) return _plots.by_feature( gx, gy, gse, feature=feature, center=center, ylabel="Mean effect", ax=ax, title=title ) def _plot_calibration(self, *, ax, title): from . import _plots cal = self.calibration_test() ci = cal.confint() return _plots.coefficients( ["mean forest prediction", "differential forest prediction"], cal.beta, ci[:, 1].to_numpy(), ci[:, 2].to_numpy(), reference=1.0, ax=ax, title=title, xlabel="Coefficient (1 is a well-calibrated forest)", ) def _plot_projection(self, *, ax, title, data=None, terms=None): from . import _plots if data is None: raise ValueError("kind='projection' needs data=, the data the forest was fitted on") blp = self.best_linear_projection(data, terms=terms) ci = blp.confint() return _plots.coefficients( blp.coefnames, blp.beta, ci[:, 1].to_numpy(), ci[:, 2].to_numpy(), reference=0.0, ax=ax, title=title, xlabel="Effect (best linear projection)", )
[docs] def __init__(self, fml, formula, engine, centering_s, options): super().__init__(fml, formula, engine, centering_s, options) self.treatment = formula.treatment self.fixed_effects = list(formula.fixed_effects) self._scores_path = None
def _extra_lines(self): fe = " + ".join(self.fixed_effects) if self.fixed_effects else "none" return [f" fixed effects: {fe}"] # ------------------------------------------------------------- scores def _scores(self): """Per training row, in storage order: the out-of-bag estimate, its variance, the estimated variance of the residualized treatment given the features, and the doubly robust score. Computed once, to a file in the run directory (a memory-mapped array).""" e = self._engine if self._scores_path is None: st = e.store group = e.variance_group_size aux_trees = max(100, -(-e.num_trees // 4 // group) * group) aux = ForestEngine( kind="regression", target=self._aux_target, num_trees=aux_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, 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 + 1, verbose=e.verbose, ) aux.fit_store(st, e.workdir / "debiasing") self._aux = aux mean_abs = mean = 0.0 for (_, w, _, sw, _), z in zip( st.chunks_weighted(e.chunk_rows), st.instrument_chunks(e.chunk_rows), strict=True ): prod = w * (z if z.size else w) mean_abs += float(np.dot(sw, np.abs(prod))) mean += float(np.dot(sw, prod)) total = float(st.weights().sum()) floor = self._denominator_floor(mean_abs / total, mean / total) self._floor_value = floor path = e.workdir / "scores.npy" sc = np.lib.format.open_memmap(path, mode="w+", dtype=np.float64, shape=(st.n, 4)) a = 0 for (bins, w, y, units), z in zip( st.chunks(e.chunk_rows), st.instrument_chunks(e.chunk_rows), strict=True ): tau, var = e._predict_bins(bins, units, True, oob=True) vhat = aux._predict_bins(bins, units, False, oob=True) # keep the denominator away from zero, with its sign vhat = np.where(vhat < 0, -1.0, 1.0) * np.maximum(np.abs(vhat), floor) k = bins.shape[0] sc[a : a + k, 0] = tau sc[a : a + k, 1] = var sc[a : a + k, 2] = vhat sc[a : a + k, 3] = tau + (z if z.size else w) / vhat * (y - tau * w) a += k sc.flush() del sc self._scores_path = path self._check_scores(np.load(path, mmap_mode="r")) return np.load(self._scores_path, mmap_mode="r") _floor_value = 0.0 def _denominator_floor(self, mean_abs, mean): """The smallest size of the denominator of the scores' correction, given the average of the absolute products it is estimated from and their (signed) average, which is the average denominator.""" return 1e-4 * mean_abs def _check_scores(self, sc): """Warn about what the scores' denominators say about the fit."""
[docs] def oob_predictions( self, variance: bool | None = None, n_threads: int | None = None ) -> pl.DataFrame: """See `ForestResult.oob_predictions`. The estimates are computed once and kept in the run directory.""" variance = self._wants_variance(variance) with thread_scope(n_threads): sc = self._scores() out = {"row_id": self._engine.store.row_ids(), "tau": np.asarray(sc[:, 0])} if variance: out["variance"] = np.asarray(sc[:, 1]) return pl.DataFrame(out)
# --------------------------------------------------------------- ATE
[docs] def average_treatment_effect(self, n_threads: int | None = None) -> TreatmentEffect: """The average of the treatment effect over the training rows, with a standard error. Each row's score is its out-of-bag effect estimate plus a correction from its residual: ``tau_i + (w_i / v_i) (y_i - tau_i w_i)``, with `y_i` and `w_i` the residualized outcome and treatment, and `v_i` an estimate of the variance of `w_i` given the features (a regression forest of the squared residualized treatment). The average of the scores is the estimate; its standard error is that of a mean of the scores, clustered when the forest was fitted with ``cluster=``. With sample weights the average is weighted, and its standard error is that of a weighted mean: ``sqrt(m / (m - 1) sum(w^2 (score - estimate)^2)) / sum(w)`` for m rows. For an instrumental forest the score is ``tau_i + (z_i / c_i) (y_i - tau_i w_i)``, with `z_i` the residualized instrument and `c_i` an estimate of the covariance of `w_i` and `z_i` given the features (at least a tenth of its average in size, with its sign), and the average is of the local effects: each row's effect among the rows its instrument moves. Returns ------- TreatmentEffect """ with thread_scope(n_threads): sc = self._scores() st = self._engine.store n = st.n gamma_all = np.asarray(sc[:, 3]) ok = np.isfinite(gamma_all) m = int(ok.sum()) if m < 2: raise ValueError("fewer than two rows have an out-of-bag estimate") sw = st.weights() total = float(sw[ok].sum()) ate = float(np.average(gamma_all[ok], weights=sw[ok])) dev = np.where(ok, sw * (gamma_all - ate), 0.0) # weighted deviations, to be summed n_clusters = {} cluster = self.options.get("cluster") if st.clustered: units = np.concatenate([u for _, _, _, u in st.chunks(self._engine.chunk_rows)]) sums = ( pl.DataFrame({"u": units[ok], "d": dev[ok]}) .group_by("u") .agg(pl.col("d").sum())["d"] .to_numpy() ) g = sums.size if g < 2: raise ValueError("fewer than two clusters") var = g / (g - 1) * float((sums**2).sum()) / total**2 vcov_type, n_clusters = f"CRV1:{cluster}", {cluster: g} df = g - 1 else: var = m / (m - 1) * float((dev[ok] ** 2).sum()) / total**2 vcov_type, df = "iid", m - 1 return TreatmentEffect( fml=self.fml, depvar=self.outcome, coefnames=["ATE"], beta=np.array([ate]), vcov=np.array([[var]]), vcov_type=vcov_type, df_t=df, n_obs=m, n_clusters=n_clusters, n_dropped=n - m, weights=self.weights, estimand=self._ate_estimand, diagnostics={"timings": dict(self.timings)}, )
# --------------------------------------------- projections and tests def _projection(self, names, blocks, vcov, estimand, n_total): """A least-squares fit on the blocks; `vcov` as `parse_vcov` returns it.""" estimator, key = vcov beta, v, n, g = ols(blocks, len(names), estimator) return LinearProjection( fml=self.fml, depvar=self.outcome, coefnames=list(names), beta=beta, vcov=v, vcov_type=key, df_t=(g - 1) if g else n - len(names), n_obs=n, n_clusters={self.options["cluster"]: g} if g else {}, n_dropped=n_total - n, weights=self.weights, estimand=estimand, )
[docs] def best_linear_projection( self, data, terms: list[str] | None = None, vcov: str | None = None, n_threads: int | None = None, ) -> LinearProjection: # fmt: skip """The best linear projection of the treatment effect on features: the regression of each row's doubly robust score (see `average_treatment_effect`) on an intercept and `terms`. It tells how the average effect differs with the terms, without assuming that the effect is linear in them. Parameters ---------- data : str, polars.DataFrame or polars.LazyFrame The data the forest was fitted on (the same rows in the same order), with the columns of `terms`. The terms' columns are read into memory for the rows that were fitted. terms : list of str, optional Columns to project on. Default: the forest's features. vcov : str or dict, optional The variance estimator, spelled as in hdfe-stream: ``"HC0"``, ``"HC1"`` (or ``"hetero"``), ``"HC2"`` or ``"HC3"``, or the forest's clustering as ``{"CRV1": "school"}`` (or ``"CRV1:school"``), with the column the forest was fitted with as ``cluster=``; the names are case-insensitive. CRV1 has hdfe-stream's small-sample factor, G/(G-1) (n-1)/(n-k), and its p-values use G-1 degrees of freedom. Default ``"HC3"``, or CRV1 by the forest's clusters when it was fitted with ``cluster=``. n_threads : int, optional Returns ------- LinearProjection Coefficients ``Intercept`` and one per term. """ terms = list(self.features if terms is None else terms) with thread_scope(n_threads): sc = self._scores() st = self._engine.store gamma = np.asarray(sc[:, 3]) ids = st.row_ids() frame = ( as_lazy(data) .with_row_index("row_id") .select(pl.col("row_id").cast(pl.Int64), *terms) .join(pl.DataFrame({"row_id": ids}).lazy(), on="row_id", how="inner") .sort("row_id") .collect() ) if frame.height != st.n or not np.array_equal(frame["row_id"].to_numpy(), ids): raise ValueError( "data does not hold the rows the forest was fitted on: " f"{frame.height:,} of its {st.n:,} rows were found" ) a_mat = frame.select(terms).to_numpy().astype(np.float64) if not np.isfinite(a_mat).all(): raise ValueError("missing or infinite values in the terms") ok = np.isfinite(gamma) cluster = self.options.get("cluster") if vcov is None: vcov = {"CRV1": cluster} if st.clustered else "HC3" vcov = parse_vcov(vcov, cluster) units = None if vcov[0] == "CRV1": units = np.concatenate([u for _, _, _, u in st.chunks(self._engine.chunk_rows)])[ok] x = np.column_stack([np.ones(int(ok.sum())), a_mat[ok]]) y = gamma[ok] weight = st.weights()[ok] step = 200_000 def blocks(): for a in range(0, y.size, step): yield ( x[a : a + step], y[a : a + step], None if units is None else units[a : a + step], weight[a : a + step], ) return self._projection( ["Intercept", *terms], blocks, vcov, "best linear projection of the treatment effect", st.n, )
[docs] def calibration_test( self, vcov: str | dict | None = None, n_threads: int | None = None ) -> LinearProjection: """A test of whether the forest's effect estimates are well calibrated (the test of Chernozhukov, Demirer, Duflo and Fernandez-Val's best linear predictor, as grf runs it). It regresses the residualized outcome on the residualized treatment times the average out-of-bag estimate (``mean.forest.prediction``) and times the estimate's deviation from that average (``differential.forest.prediction``). With sample weights the regression is weighted, and the average estimate is a weighted mean. A coefficient of one on the first means the average effect is right. A coefficient of one on the second means the heterogeneity is right; a positive coefficient (significant, in a one-sided test: halve the p-value of a positive estimate) means the forest found heterogeneity that is there; zero means it found none. Parameters ---------- vcov : str or dict, optional As in `best_linear_projection`: default ``"HC3"``, or CRV1 by the forest's clusters. n_threads : int, optional Returns ------- LinearProjection """ with thread_scope(n_threads): sc = self._scores() e = self._engine st = e.store tau = np.asarray(sc[:, 0]) ok = np.isfinite(tau) mean = float(np.average(tau[ok], weights=st.weights()[ok])) cluster = self.options.get("cluster") if vcov is None: vcov = {"CRV1": cluster} if st.clustered else "HC3" vcov = parse_vcov(vcov, cluster) def blocks(): a = 0 for _, w, y, sw, u in st.chunks_weighted(e.chunk_rows): t = tau[a : a + w.size] a += w.size m = np.isfinite(t) x = np.column_stack([w * mean, w * (t - mean)])[m] yield x, y[m], u[m], sw[m] return self._projection( ["mean.forest.prediction", "differential.forest.prediction"], blocks, vcov, "calibration test of the effect estimates", st.n, )
[docs] class InstrumentalForestResult(CausalForestResult): """A fitted instrumental forest: estimates of the effect of the treatment among the rows that the instrument moves, as a function of the features. See `CausalForestResult`, whose methods work on the instrument's local effects; `instrument` names the instrument. `calibration_test` is not available. """ _title = "Instrumental forest" _plot_kinds = ("effects", "heterogeneity", "importance", "projection") _aux_target = "wz" _ate_estimand = ( "average of the local effects of the treatment, among those the instrument moves" ) instrument: str | None = None def _extra_lines(self): return [f" instrument: {self.instrument}", *super()._extra_lines()] # The correction divides by the covariance of the treatment and the instrument given # the features, estimated row by row; where the instrument is weak that is noisy # and can be near zero or of the wrong sign, and a few rows then carry the whole # average. It is kept at least this share of its average (in size, with its sign). _floor_share = 0.1 def _denominator_floor(self, mean_abs, mean): return self._floor_share * abs(mean) def _check_scores(self, sc): c = np.abs(np.asarray(sc[:, 2])) weak = int((c <= self._floor_value * (1 + 1e-9)).sum()) if weak >= 0.01 * c.size: warnings.warn( f"the instrument looks weak for {weak:,} rows ({weak / c.size:.1%}): its estimated " f"covariance with the treatment, given the features, is under {self._floor_share:.0%} " "of the average, and the scores treat it as if it were that large there. The " "effects at those rows are poorly determined, and the average effect leans on the " "forest's estimates for them", stacklevel=3, ) def calibration_test(self, *args, **kwargs): raise NotImplementedError( "calibration_test is for causal forests; for an instrumental forest, " "best_linear_projection gives the heterogeneity" )
[docs] class QuantileForestResult(ForestResult): """A fitted quantile forest: honest trees that keep the outcomes of their estimation rows, so that any conditional quantile of the outcome can be read off at prediction time. See `ForestResult`. Attributes ---------- quantiles : list of float The quantile levels the trees were grown to separate, which are also the default levels of `predict`. """ _title = "Quantile forest" _plot_kinds = ("importance",)
[docs] def __init__(self, fml, formula, engine, centering_s, options): super().__init__(fml, formula, engine, centering_s, options) self.quantiles = [float(q) for q in engine.qlev] self._levels_now = None
def _extra_lines(self): stored = self._engine.forest_bytes() / 2**20 return [ f" quantiles: {', '.join(f'{q:g}' for q in self.quantiles)}", f" forest on disk: {stored:,.0f} MB", ] def _levels(self, quantiles): q = self.quantiles if quantiles is None else quantiles return self._engine._levels(q) @staticmethod def _names(levels): return [f"q{q:g}" for q in levels]
[docs] def predict( self, data, quantiles=None, n_threads: int | None = None, *, keep: list[str] | None = None, output=None, batch_rows: int | None = None, ): """Conditional quantiles of the outcome at the rows of `data`, read and predicted in batches. Parameters ---------- data : str, polars.DataFrame or polars.LazyFrame A Parquet path or glob, or a frame, with the feature columns. quantiles : float or sequence of float, optional Levels strictly between 0 and 1. Default: the levels the trees were grown for (`quantiles`). Any levels can be asked for; the forest does not have to be fitted again. n_threads : int, optional keep, output, batch_rows As in `ForestResult.predict`. Returns ------- polars.DataFrame or pathlib.Path One row per row of `data`: any `keep` columns, then one column for each level, named ``q0.1``, ``q0.5`` and so on. A quantile is the smallest outcome whose weight in the forest reaches the level; it is one of the training outcomes. With `output`, the path. """ self._levels_now = self._levels(quantiles) try: return super().predict( data, variance=False, n_threads=n_threads, keep=keep, output=output, batch_rows=batch_rows, ) # fmt: skip finally: self._levels_now = None
def _predict_batch(self, df, variance, include_fixed_effects, new_groups, keep): levels = self._levels_now x = self._feature_matrix(df) frame = pl.DataFrame(self._engine.predict_quantiles(x, levels), schema=self._names(levels)) if keep: clash = [c for c in keep if c in frame.columns] if clash: raise ValueError( f"keep: {clash} would have the name of a column of the predictions " f"({frame.columns}); rename them in the data" ) frame = pl.concat([df.select(keep), frame], how="horizontal") return frame
[docs] def oob_predictions(self, quantiles=None, n_threads: int | None = None) -> pl.DataFrame: """Out-of-bag quantiles at the rows the forest was fitted on: each row's estimate pools only the trees whose subsample does not contain the row (or its cluster). Returns ------- polars.DataFrame ``row_id`` and a column for each level, as `predict` names them. """ levels = self._levels(quantiles) with thread_scope(n_threads): out = self._engine.predict_quantiles_oob(levels) frame = pl.DataFrame(out, schema=self._names(levels)) return frame.insert_column(0, pl.Series("row_id", self._engine.store.row_ids()))
[docs] def oob_score(self, quantiles=None, n_threads: int | None = None) -> pl.DataFrame: """How well the out-of-bag quantiles fit the outcome: for each level, the mean pinball (check) loss, which the true quantile minimizes, and the share of outcomes at or below the estimate, which should be near the level. Weighted by the sample weights, if any. Returns ------- polars.DataFrame ``quantile``, ``pinball_loss``, ``coverage`` and ``n`` (rows with a tree out of bag), one row for each level. """ levels = self._levels(quantiles) e = self._engine with thread_scope(n_threads): pred = e.predict_quantiles_oob(levels) y = np.concatenate([yy for _, _, yy, _, _, _ in e._chunks()]) sw = e.store.weights() rows = [] for k, q in enumerate(levels): ok = np.isfinite(pred[:, k]) err, wt = y[ok] - pred[ok, k], sw[ok] loss = np.average(np.where(err >= 0, q * err, (q - 1) * err), weights=wt) rows.append( (float(q), float(loss), float(np.average(err <= 0, weights=wt)), int(ok.sum())) ) return pl.DataFrame( rows, schema=["quantile", "pinball_loss", "coverage", "n"], orient="row" )