Source code for penalized_stream.double_selection_iv

"""Post-double-selection with instruments (Chernozhukov, Hansen and Spindler
2015; Belloni, Chen, Chernozhukov and Hansen 2012).

One endogenous treatment d, excluded instruments z and many candidate
controls x. With a few instruments, lassos of the outcome, of d and of each
instrument on the controls select controls; the effect of d is the 2SLS
coefficient with the union of the selected controls, instrumented by z. With
many instruments (``select_instruments=True``), a lasso of d on the
instruments and the controls selects the instruments, a lasso of its
post-lasso fit on the controls selects the controls that predict the part
of d the instruments explain, and the union then also has the controls the
lassos of the outcome and of d select (the selection steps of hdm's
`rlassoIV`). With ``method="partialling_out"``, the estimate is instead 2SLS
on each variable's residual from its own selected controls (hdm's).

All the lassos come from one pass over the data (the fixed effects
partialled out), plus one pass per iteration of the plug-in penalty's
loadings; the final 2SLS regression is an hdfe-stream fit, with its first
stage and standard errors.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any

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

from . import _design, _fit, _sup_score
from ._solver import moments
from .double_selection import (
    DoubleSelection,
    _check_groups,
    _cluster_columns,
    _final_sample,
    _select,
)

_FITTED = "__ps_first_stage_fit"


[docs] @dataclass class DoubleSelectionIV(DoubleSelection): """What the selection steps chose (``result.double_selection``), with the instruments: `selected` has the controls selected for the outcome, the treatment and each instrument (or, with ``select_instruments``, for the outcome, the treatment, the first stage and its fit).""" endogenous: str = "" exogenous: list = field(default_factory=list) instruments: list = field(default_factory=list) instruments_used: list = field(default_factory=list) select_instruments: bool = False method: str = "union" sup_score: _sup_score.SupScoreTest | None = None def summary_text(self) -> str: head = super().summary_text() n_z = len(self.instruments) if self.select_instruments: line = (f" instruments: {len(self.instruments_used)} of {n_z} selected " f"({', '.join(self.instruments_used[:8])}" + (", ..." if len(self.instruments_used) > 8 else "") + ")") else: line = f" instruments: {', '.join(self.instruments)}" estimate = ("partialling-out (residuals on each lasso's selection)" if self.method == "partialling_out" else "2SLS on the union") text = head + "\n" + line + f"\n estimate: {estimate}" if self.sup_score is not None: text += "\n" + self.sup_score.summary_text() return text
def _names(fml, unpenalized, lf): return _design.parse_model(fml, unpenalized, lf) def _projection(design, t, cols): """The OLS slopes of the combination `t` of the design's variables on `cols` (with the intercept or fixed effects partialled out), as a vector over the design's variables (zero outside `cols`).""" order = [design.depvar, *design.names] pos = {nm: i for i, nm in enumerate(order)} idx = [pos[c] for c in dict.fromkeys(cols)] cp = design.cp G, s = cp.total(), cp.sums.sum(axis=0) Gt = G @ t gram = np.empty((1 + len(idx), 1 + len(idx))) gram[0, 0] = t @ Gt gram[0, 1:] = gram[1:, 0] = Gt[idx] gram[1:, 1:] = G[np.ix_(idx, idx)] sums = np.concatenate([[s @ t], s[idx]]) m = moments(gram, sums, cp.weight_sums.sum(), int(cp.counts.sum()), standardize=False) keep = [j for j in range(len(idx)) if m.usable[j]] a = np.zeros(len(order)) if keep: b = np.linalg.lstsq(m.C[np.ix_(keep, keep)], m.c[keep], rcond=None)[0] a[[idx[j] for j in keep]] = b return a def _unit(design, name): order = [design.depvar, *design.names] e = np.zeros(len(order)) e[order.index(name)] = 1.0 return e def _combination(design, a, exprs): """The combination `a` of the design's variables as a Polars expression, from `exprs` (name -> expression).""" order = [design.depvar, *design.names] expr = pl.lit(0.0) for nm, aj in zip(order, a, strict=True): if aj != 0.0: expr = expr + float(aj) * exprs[nm] return expr
[docs] def double_selection_iv_stream(fml: str, data: Any, *, controls: str, unpenalized=None, select_instruments: bool = False, method: str = "union", 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, sup_score: bool = False, sup_score_options: dict | None = None, **options): """Post-double-selection with instruments: the 2SLS effect of an endogenous treatment, controlling for the controls lassos select. Parameters ---------- fml : str An IV formula, ``"y ~ w + [d ~ z1 + z2] | fe1 + fe2"``: the outcome, any exogenous regressors w (always included and never penalized; ``1`` if none), the endogenous treatment d and its excluded instruments, 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. select_instruments : bool, default False False: every instrument is used, and the controls are those selected for the outcome, the treatment or any instrument (hdm's `rlassoIVselectX`). True: a lasso of the treatment on the instruments and the controls selects the instruments (hdm's `rlassoIV`), for when there are many. method : {"union", "partialling_out"}, default "union" ``"union"``: the 2SLS regression of the outcome on the treatment and the union of the selected controls, instrumented by the instruments (and the union), as Stata's ``ivlasso`` reports under "PDS". ``"partialling_out"``: the outcome, the treatment and the instruments are each replaced by their residual from the post-lasso fit on their own selected controls, and the result is the 2SLS regression of the residuals (hdm's estimate, ``ivlasso``'s "CHS"). With ``select_instruments``, the single instrument is the residual of the first-stage fit, and the treatment's residual uses the controls selected for that fit, as in hdm's `rlassoIV`. penalty : str or float, default "rigorous" The lassos' penalty: ``"rigorous"`` (the plug-in penalty), ``"cv"``, ``"cv_1se"``, a criterion, or a value. vcov : default "hetero" The 2SLS 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, as in `double_selection_stream`: each factor of the controls (and, with ``select_instruments``, of the instruments) is selected or left out as a block. Not with ``penalty="rigorous"``. sup_score : bool, default False Also run the sup-score test (Belloni, Chen, Chernozhukov and Hansen 2012; Chernozhukov, Hansen and Spindler 2015), whose test of the treatment's effect and confidence set stay valid however weak the instruments are (``result.double_selection.sup_score``, a `SupScoreTest`). It takes one more pass over the data. sup_score_options : dict, optional ``null`` (the effect tested; default 0), ``method`` (``"bound"``, the default: the critical value c Phi^-1(1 - (1 - level) / (2p)) for p instruments, as lassopack's `ivlasso`, with the confidence set solved exactly; or ``"bootstrap"``, the multiplier bootstrap's p-value, with the set read off the grid), ``level`` (0.95), ``c`` (1.1), ``draws`` (500, for the bootstrap), ``grid`` (``(low, high, points)`` or a list of values; default the 2SLS estimate plus or minus 20 standard errors, 101 points) and ``seed`` (for the bootstrap; default `seed`). **options hdfe-stream's options, for the pass and the final regression. Returns ------- HDFEResult The 2SLS regression (with ``method="partialling_out"``, of the residuals, so it has the treatment's coefficient and, without fixed effects, an intercept), with its first stage (``first_stage``, ``f_stat_1st_stage``) and ``double_selection`` (a `DoubleSelectionIV`) saying what was selected for what. """ if method not in ("union", "partialling_out"): raise ValueError(f"method must be 'union' or 'partialling_out'; got {method!r}") ss_options = _sup_score.check_options(sup_score_options) if sup_score else None if sup_score_options is not None and not sup_score: raise ValueError("sup_score_options needs sup_score=True") if not isinstance(controls, str) or not controls.strip(): raise ValueError("controls must be a right-hand side, e.g. 'x1 + x2 + i(region)'") specs = parse_formula(fml) if len(specs) != 1: raise ValueError(f"{fml!r} describes {len(specs)} models; give one at a time") spec = specs[0] if spec.iv is None: raise ValueError("fml needs an endogenous treatment and its instruments, " "'y ~ w + [d ~ z1 + z2] | fe'; without instruments use " "double_selection_stream") lf = _design.as_lazy(data) fe_part = f" | {spec.fe}" if spec.fe else "" endog_rhs, fs_rhs = spec.iv _, yname, second, _, fe, exprs = _names(f"{spec.dep} ~ {spec.rhs}{fe_part}", None, lf) _, _, endog, _, _, _ = _names(f"{spec.dep} ~ {endog_rhs}", None, lf) if len(endog) != 1: raise ValueError(f"one endogenous treatment is supported; got {endog}") d = endog[0] exog = [nm for nm in second if nm != d] _, _, first, _, _, _ = _names(f"{spec.dep} ~ {fs_rhs}{fe_part}", None, lf) z_alone = [nm for nm in first if nm not in exog and nm != d] if not z_alone: raise ValueError("the formula has no excluded instruments") cfml = f"{spec.dep} ~ {controls}{fe_part}" _, _, cnames, unpen, _, cexprs = _names(cfml, unpenalized, lf) for what, names in (("exogenous regressors", exog), ("the treatment", [d]), ("instruments", z_alone)): clash = [c for c in cnames if c in names] if clash: raise ValueError(f"{clash} are both controls and {what}") # one pass: [y, exogenous, d, instruments, controls], the instruments as # written (their compiled names, C(q)[T.2], are not a formula). Their # names are those of this formula: an interaction's coding depends on the # other terms (C(q):x0 alone has every level of q; beside a control x0, # all but the first) parts = [spec.rhs, fs_rhs, controls] if isinstance(unpenalized, str): parts.append(unpenalized) big = f"{spec.dep} ~ {' + '.join(parts)}{fe_part}" _, _, bignames, _, _, bigexprs = _names(big, None, lf) others = {*exog, d, *cnames, *unpen} z = [nm for nm in bignames if nm not in others] if not z: raise ValueError("the formula has no excluded instruments") _check_groups(groups, penalty, z + cnames if select_instruments else cnames, "a control or an instrument" if select_instruments else "a control") all_exprs = {**cexprs, **bigexprs, **exprs} rigorous = penalty == "rigorous" needs_cv = penalty in _fit.CV_RULES cl = _cluster_columns(vcov, cluster) if rigorous else None ss_cluster = _cluster_columns(vcov, cluster) if sup_score else None carry = list(dict.fromkeys([*(cl or []), *(ss_cluster or [])])) 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 or sup_score, carry=carry, options=options) missing = [nm for nm in [*exog, d, *z, *cnames] if nm not in design.names] if missing: raise ValueError(f"could not find {missing} among the compiled columns") # the exogenous regressors are in every lasso, unpenalized xs = [*exog, *cnames] always = [*exog, *unpen] kw = dict(penalty=penalty, standardize=standardize, tol=tol, cluster=cl, rigorous_options=rigorous_options, groups=groups, weights_type=weights_type) selected, penalties = {}, {} def lasso(key, target, names, derived=None): sel, lam, _ = _select(design, target, names, always, derived=derived, **kw) selected[key] = [c for c in sel if c not in exog] penalties[key] = lam return sel partial = method == "partialling_out" lasso(yname, yname, xs) if not (partial and select_instruments): # hdm's partialling-out has no use for it lasso(d, d, xs) if select_instruments: key_fs, key_fit = f"{d} (first stage)", f"{d} (first-stage fit)" sel = lasso(key_fs, d, [*z, *xs]) used = [c for c in z if c in sel] if not used: design.cp.cleanup() raise ValueError(f"the lasso of {d} on the instruments and controls selected no " "instrument") selected[key_fs] = [c for c in selected[key_fs] if c not in z] fitted = _projection(design, _unit(design, d), [*used, *selected[key_fs], *always]) order = [design.depvar, *design.names] stored = {nm: pl.col(nm) for nm in order} lasso(key_fit, _FITTED, xs, derived=(fitted, _combination(design, fitted, stored))) else: used = list(z) for zj in z: lasso(zj, zj, xs) sums = variance = None if sup_score: # before the final sample removes the saved rows sel_d = selected.get(d) if sel_d is None: # hdm's partialling-out with select_instruments skips it sel_d = [c for c in _select(design, d, xs, always, **kw)[0] if c not in exog] sums, variance = _sup_score_sums(design, yname, d, z, selected[yname], sel_d, always, vcov=vcov, cluster=ss_cluster, bootstrap=ss_options["method"] == "bootstrap") union = [c for c in cnames if c in unpen or any(c in s for s in selected.values())] passthrough = {k: v for k, v in options.items() if k in _design.PASSTHROUGH} icpt = [] if fe else ["Intercept"] all_exprs["Intercept"] = pl.lit(1.0) if partial: def resid(name, key, t=None): t = _unit(design, name) if t is None else t b = _projection(design, t, [*selected[key], *always]) return _combination(design, t - b, all_exprs) y_expr = resid(yname, yname) if select_instruments: b = _projection(design, fitted, [*selected[key_fit], *always]) d_expr = _combination(design, _unit(design, d) - b, all_exprs) z_name = f"{d}_hat" instruments = [(z_name, _combination(design, fitted - b, all_exprs))] else: d_expr = resid(d, d) instruments = [(zj, resid(zj, zj)) for zj in z] sample = _final_sample(design.cp) x_vars = [*icpt, d] z_vars = [*icpt, *(nm for nm, _ in instruments)] columns = ([("Intercept", all_exprs["Intercept"])] if icpt else []) + \ [(d, d_expr), *instruments] y_cols = [(yname, y_expr)] else: sample = _final_sample(design.cp) x_vars = [*icpt, *exog, d, *union] z_vars = [*icpt, *exog, *used, *union] columns = [(nm, all_exprs[nm]) for nm in dict.fromkeys(x_vars + z_vars)] y_cols = [(yname, all_exprs[yname])] est = StreamingHDFE(y=y_cols, x=columns, fe=fe, weights=weights, weights_type=weights_type, models=[{"fml": fml, "y": yname, "x": x_vars, "iv": {"endog": [d], "z": z_vars}}], **passthrough) result = est.fit(sample, vcov=vcov) test = None if sup_score: if ss_options["seed"] is None: ss_options["seed"] = seed test = _sup_score.sup_score_test(sums, options=ss_options, variance=variance, center=float(result.coef()[d]), se=float(result.se[result.coefnames.index(d)])) result.double_selection = DoubleSelectionIV( treatments=[d], controls=list(cnames), unpenalized=list(unpen), selected=selected, union=union, penalty=penalty, penalties=penalties, loadings_cluster=cl, endogenous=d, exogenous=exog, instruments=z, instruments_used=used, select_instruments=select_instruments, method=method, sup_score=test) return result
def _sup_score_sums(design, yname, d, z, sel_y, sel_d, always, *, vcov, cluster, bootstrap): """The sup-score test: the outcome and the treatment partialled on their selected controls (post-lasso), the instruments on the always-included regressors only, as lassopack's `ivlasso`.""" def resid(name, cols): t = _unit(design, name) return t - _projection(design, t, cols) t_y = resid(yname, [*sel_y, *always]) t_d = resid(d, [*sel_d, *always]) T_z = np.vstack([resid(zj, always) if always else _unit(design, zj) for zj in z]) if cluster is not None: variance = "cluster" elif vcov_key(vcov) == "iid": variance = "iid" else: variance = "hetero" sums = _sup_score.accumulate(design, t_y, t_d, T_z, variance=variance, cluster=cluster, bootstrap=bootstrap) return sums, variance