Source code for penalized_stream.double_selection

"""Post-double-selection (Belloni, Chernozhukov and Hansen 2014).

For each treatment d and for the outcome y, a lasso of that variable on the
candidate controls selects controls; the effect of d is then the
least-squares coefficient of y on the treatments and the union of the
selected controls, with ordinary (robust or clustered) standard errors.
Selecting the controls that predict the treatment as well as those that
predict the outcome is what makes that inference valid after selection.

All the lassos come from one pass over the data (cross-products of the
outcome, the treatments and the controls, the fixed effects partialled out),
plus one pass per iteration of the plug-in penalty's loadings; the final
regression is an hdfe-stream fit, so its result reports and exports as any
other.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any

import numpy as np
import polars as pl
from hdfe_stream import StreamingHDFE
from hdfe_stream.core.results_base import vcov_key

from . import _design, _fit, _groups
from ._folds import FOLD


class _Subset:
    """The cross-products of a subset of the variables (index into the parent).

    With `target`, ``(name, a, expr)``, the first variable is instead the
    linear combination ``a`` of all the parent's variables (a fitted value,
    say): its cross-products come from the parent's, and the saved rows get
    the column `name`, computed by `expr` from the stored columns.
    """

    def __init__(self, cp, idx, target=None):
        self._cp, self._idx = cp, np.asarray(idx)
        ix = np.ix_(self._idx, self._idx)
        self.gram = cp.gram[(slice(None), *ix)]
        self.sums = cp.sums[:, self._idx]
        self._target = target
        if target is not None:
            a = np.asarray(target[1], dtype=float)
            ga = cp.gram @ a                                   # (S, p)
            self.gram = self.gram.copy()
            self.sums = self.sums.copy()
            self.gram[:, 0, 1:] = ga[:, self._idx[1:]]
            self.gram[:, 1:, 0] = ga[:, self._idx[1:]]
            self.gram[:, 0, 0] = ga @ a
            self.sums[:, 0] = cp.sums @ a
        self.weight_sums, self.counts = cp.weight_sums, cp.counts
        self.n_obs, self.k_fe, self.n_levels = cp.n_obs, cp.k_fe, cp.n_levels
        self.weight_column, self.diagnostics = cp.weight_column, cp.diagnostics

    @property
    def n_splits(self):
        return self.gram.shape[0]

    def total(self):
        return self.gram.sum(axis=0)

    def excluding(self, s):
        keep = [g for i, g in enumerate(self.gram) if i != s]
        return np.sum(keep, axis=0)

    def rows(self):
        return self._apply(self._cp.rows())

    def _apply(self, rows):
        if self._target is not None:
            rows = rows.with_columns(self._target[2].alias(self._target[0]))
        return rows


@dataclass
class _SubDesign:
    depvar: str
    names: list
    unpenalized: list
    fe: list
    n_folds: int
    cp: Any
    shift: np.ndarray
    weights_type: str


[docs] @dataclass class DoubleSelection: """What the selection steps chose (``result.double_selection``).""" treatments: list[str] controls: list[str] unpenalized: list[str] selected: dict # variable (outcome or treatment) -> selected controls union: list[str] penalty: str | float penalties: dict # variable -> the penalty its lasso used loadings_cluster: list | None def summary_text(self) -> str: lines = [f"post-double-selection: {len(self.union)} of {len(self.controls)} " f"controls selected (penalty: {self.penalty})"] for v, s in self.selected.items(): lines.append(f" {v}: {len(s)} selected" + (f" ({', '.join(s[:8])}" + (", ..." if len(s) > 8 else "") + ")" if s else "")) if self.unpenalized: lines.append(f" always included: {', '.join(self.unpenalized)}") return "\n".join(lines)
def _group_ids(names, groups, unpen): """`groups` restricted to `names` (one lasso's covariates), as ids.""" if groups is None: return None if isinstance(groups, dict): groups = {lab: [m for m in ([v] if isinstance(v, str) else v) if m in names] for lab, v in groups.items()} groups = {lab: v for lab, v in groups.items() if v} return _groups.assign(names, groups, unpen)[1] def _check_groups(groups, penalty, names, what="a control"): if groups is None: return if penalty == "rigorous": raise ValueError("groups= is not available with penalty='rigorous' (the plug-in " "penalty is for the lasso); choose the penalty by cross-validation " "('cv', 'cv_1se'), a criterion or a value") if isinstance(groups, dict): for lab, v in groups.items(): for m in [v] if isinstance(v, str) else v: if m not in names: raise ValueError(f"groups: {m!r} (in {lab!r}) is not {what}") elif groups != "factors": raise ValueError("groups must be None, 'factors' or a dict of group -> names") def _select(design, target, names, unpen, *, penalty, standardize, tol, cluster, rigorous_options, groups, weights_type, derived=None): """One lasso of `target` on `names` from the design's cross-products: (the selected penalized names, the penalty used, the coefficients). `derived`, ``(a, expr)``: the target is that linear combination of the design's variables instead of a column.""" order = [design.depvar, *design.names] pos = {nm: i for i, nm in enumerate(order)} idx = [0 if derived is not None else pos[target]] + [pos[c] for c in names] sub_cp = _Subset(design.cp, idx, None if derived is None else (target, *derived)) shift = design.shift[idx].copy() if derived is not None: shift[0] = float(design.shift @ derived[0]) sub = _SubDesign(depvar=target, names=list(names), unpenalized=list(unpen), fe=design.fe, n_folds=design.n_folds, cp=sub_cp, shift=shift, weights_type=weights_type) gids = _group_ids(names, groups, unpen) if penalty == "rigorous": from ._rigorous import rigorous_penalty lam, loadings, _ = rigorous_penalty(sub, cluster=cluster, standardize=standardize, tol=tol, **(rigorous_options or {})) path = _fit.fit(sub, l1_ratio=1.0, penalty=lam, n_lambdas=100, lambda_min_ratio=None, standardize=standardize, tol=tol, loadings=loadings, cv=False) i = len(path.lambdas) - 1 else: path = _fit.fit(sub, l1_ratio=1.0, penalty=penalty, n_lambdas=100, lambda_min_ratio=None, standardize=standardize, tol=tol, cv=penalty in _fit.CV_RULES, groups=gids) i, _ = _fit.choose(path, penalty) coef = path.coef[i] selected = [c for c, b in zip(names, coef, strict=True) if b != 0.0 and c not in unpen] return selected, float(path.lambdas[i]), coef def _final_sample(cp): sample = cp.sample(check=False).filter(pl.col("in_sample")).drop( ["in_sample", "dropped_because", cp.row_id, FOLD], strict=False) cp.cleanup() return sample def _cluster_columns(vcov, cluster): if cluster is not None: return [c.strip() for c in cluster.split("^")] key = vcov_key(vcov) if key.startswith("CRV"): spec = key.split(":", 1)[1] if "+" in spec: return None # multi-way: heteroskedastic loadings return [c.strip() for c in spec.split("^")] return None
[docs] def double_selection_stream(fml: str, data: Any, *, controls: str, unpenalized=None, penalty: str | float = "rigorous", vcov="hetero", cluster: str | None = None, weights=None, weights_type: str = "aweights", n_folds: int = 5, fold_by: str | None = None, seed: int = 0, standardize: bool = True, tol: float = 1e-7, rigorous_options: dict | None = None, groups=None, **options): """Post-double-selection: the effect of the treatments in `fml`, controlling for the controls a lasso selects. Parameters ---------- fml : str ``"y ~ d | fe1 + fe2"``: the outcome, the treatment(s) whose effects are estimated (never penalized) and the fixed effects (partialled out). data : str, Path, polars.LazyFrame or polars.DataFrame controls : str The candidate controls, as a right-hand side (``"x1 + x2 + i(region)"``). unpenalized : str or list of str, optional Controls always included (and never penalized in the lassos), as a right-hand side or names: hdm's ``I3``, the "amelioration set". penalty : str or float, default "rigorous" The lassos' penalty: ``"rigorous"`` (the plug-in penalty, for which the method's guarantees hold; hdm's and Stata's pdslasso's default), ``"cv"``, ``"cv_1se"``, a criterion, or a value. vcov : default "hetero" The final regression's vcov, as for hdfe-stream: ``"iid"``, ``"hetero"``, ``{"CRV1": "state"}``... cluster : str, optional The plug-in penalty's loadings are clustered by this column; default: the vcov's cluster, if it is one-way. weights, weights_type, n_folds, fold_by, seed, standardize, tol As for `lasso_stream` (the folds are used only by ``penalty="cv"``). rigorous_options : dict, optional As for `lasso_stream`. groups : "factors" or dict, optional Group lassos in place of the lassos: each factor of `controls` (``"factors"``), or each named group of controls, is selected or left out as a block, as in `lasso_stream`. Not with ``penalty="rigorous"``. **options hdfe-stream's options, for the pass and the final regression. Returns ------- HDFEResult The final regression, with ``double_selection`` (a `DoubleSelection`) saying what was selected for what. """ if not isinstance(controls, str) or not controls.strip(): raise ValueError("controls must be a right-hand side, e.g. 'x1 + x2 + i(region)'") lf = _design.as_lazy(data) spec, yname, treat, _, fe, exprs = _design.parse_model(fml, None, lf) # compile the controls as a model of their own, for their expressions cfml = f"{spec.dep} ~ {controls}" + (f" | {spec.fe}" if spec.fe else "") _, _, cnames, unpen, _, cexprs = _design.parse_model(cfml, unpenalized, lf) clash = [c for c in cnames if c in treat] if clash: raise ValueError(f"{clash} are both treatments and controls") _check_groups(groups, penalty, cnames) names = list(treat) + list(cnames) all_exprs = {**cexprs, **exprs} rigorous = penalty == "rigorous" needs_cv = penalty in _fit.CV_RULES cl = _cluster_columns(vcov, cluster) if rigorous else None # one pass: [y, treatments..., controls...], via a formula of all of them full_rhs = " + ".join([spec.rhs, controls] + ([unpenalized] if isinstance(unpenalized, str) else [])) big = f"{spec.dep} ~ {full_rhs}" + (f" | {spec.fe}" if spec.fe else "") design = _design.build(big, data, weights=weights, weights_type=weights_type, n_folds=n_folds if needs_cv else None, fold_by=fold_by, seed=seed, save_rows=rigorous, carry=cl or [], options=options) order = [design.depvar, *design.names] pos = {nm: i for i, nm in enumerate(order)} missing = [nm for nm in names if nm not in pos] if missing: raise ValueError(f"could not find {missing} among the compiled columns") selected, penalties = {}, {} for target in [yname, *treat]: selected[target], penalties[target], _ = _select( design, target, cnames, unpen, penalty=penalty, standardize=standardize, tol=tol, cluster=cl, rigorous_options=rigorous_options, groups=groups, weights_type=weights_type) union = [c for c in cnames if c in unpen or any(c in s for s in selected.values())] sample = _final_sample(design.cp) passthrough = {k: v for k, v in options.items() if k in _design.PASSTHROUGH} est = StreamingHDFE(y=[(yname, all_exprs[yname])], x=[(nm, all_exprs[nm]) for nm in [*treat, *union]], fe=fe, weights=weights, weights_type=weights_type, **passthrough) result = est.fit(sample, vcov=vcov) result.double_selection = DoubleSelection( treatments=list(treat), controls=list(cnames), unpenalized=list(unpen), selected=selected, union=union, penalty=penalty, penalties=penalties, loadings_cluster=cl) return result