Source code for penalized_stream.debiased

"""The debiased (desparsified) lasso: confidence intervals for the
coefficients of a lasso (van de Geer, Buhlmann, Ritov and Dezeure 2014; Zhang
and Zhang 2014), with hdi's `lasso.proj` formulas.

For each coefficient j to debias, a nodewise lasso of covariate j on the
others gives the residual direction z_j = e_j - gamma_j, rescaled so that
z_j' S e_j = 1 (S the covariates' covariance after the fixed effects). Then

    b_j = beta_j + z_j' (c - S beta)        (c: the covariates' covariance with y)

with variance sigma^2 z_j' S z_j / n under iid errors, or from the centered
scores w_i e_i z_j'x_i with "hetero" or a cluster. The initial lasso, every
nodewise lasso and the iid variance come from the cross-products of one pass;
the robust and clustered variances take one more, over the saved rows.
"""

from __future__ import annotations

import warnings
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from typing import Any

import numpy as np
from hdfe_stream.core.results_base import RegressionResult, vcov_key
from hdfe_stream.core.utils import single_blas

from . import _design, _fit
from ._nuisance import fit_nuisance
from ._scores import ScoreMeat, iter_rows
from ._solver import moments
from ._subset import sub_design


[docs] @dataclass(kw_only=True) class DebiasedLassoResult(RegressionResult): """Debiased lasso coefficients, their standard errors, intervals and tests (`summary`, `tidy`, `confint`, `wald_test`, `etable` through hdfe_stream.etable, as for any of the suite's regression results). Beyond `RegressionResult`'s attributes: Attributes ---------- lasso : dict The initial lasso's coefficients (``{name: value}``), all covariates. penalty : float The initial lasso's penalty, and `penalty_rule` how it was chosen. node_penalties : dict Each debiased coefficient's nodewise lasso penalty. sigma : float The residual standard deviation of the initial lasso, sqrt(RSS / (N - nonzero coefficients - intercept or fixed-effect parameters)). nodewise : numpy.ndarray (covariates x debiased coefficients): the rescaled directions z_j. fe_names : list of str """ lasso: dict = field(default_factory=dict) penalty: float = float("nan") penalty_rule: str = "" node_penalties: dict = field(default_factory=dict) sigma: float = float("nan") nodewise: Any = None fe_names: list = field(default_factory=list) covariates: list = field(default_factory=list) _normal_inference = True def _summary_lines(self): lines = [f"debiased lasso; initial penalty {self.penalty:.4g} ({self.penalty_rule}), " f"{sum(v != 0 for v in self.lasso.values())} of {len(self.lasso)} " f"covariates selected; sigma {self.sigma:.4g}"] if self.fe_names: lines.append("fixed effects: " + " + ".join(self.fe_names)) return lines + super()._summary_lines() def _summary_fields(self): return {**super()._summary_fields(), "estimator": "debiased lasso", "penalty": self.penalty, "penalty_rule": self.penalty_rule, "sigma": self.sigma, "fixed_effects": list(self.fe_names)} def _pyfixest_attrs(self): out = super()._pyfixest_attrs() if self.fe_names: out.update(_fixef="+".join(self.fe_names), _has_fixef=True) return out
def _cluster(key): if not key.startswith("CRV1:"): if key.startswith("CRV"): raise ValueError("the debiased lasso's clustered variance is CRV1") return None spec = key.split(":", 1)[1] if "+" in spec: raise ValueError("the debiased lasso's clustered variance is one-way") return [c.strip() for c in spec.split("^")]
[docs] def debiased_lasso_stream(fml: str, data: Any, *, penalty="cv_1se", node_penalty="cv", coefficients=None, vcov="iid", unpenalized=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, n_threads: int | None = None, **options) -> DebiasedLassoResult: """The debiased lasso: confidence intervals for a lasso's coefficients. Parameters ---------- fml : str A pyfixest formula, as for `lasso_stream` (fixed effects partialled out). data : str, Path, polars.LazyFrame or polars.DataFrame penalty : default "cv_1se" The initial lasso's penalty: ``"cv_1se"`` (hdi's default), ``"cv"``, an information criterion, ``"rigorous"`` or a value. node_penalty : default "cv" Each nodewise lasso's penalty, chosen separately for each covariate: ``"cv"`` (lambda_min), ``"cv_1se"``, a criterion or a value. coefficients : list of str, optional The coefficients to debias; default all the covariates. Each costs one nodewise lasso (on the cross-products, in memory). vcov : default "iid" ``"iid"`` (from the cross-products), ``"hetero"`` (the robust variance of hdi's ``robust=TRUE``) or ``{"CRV1": "cluster"}`` (one-way); the last two take one more pass over the rows. unpenalized, weights, weights_type, n_folds, fold_by, seed, standardize, tol As for `lasso_stream`. n_threads : int, optional Threads for the nodewise lassos. **options hdfe-stream's options (``workdir``, ``max_memory_gb``, ...). Returns ------- DebiasedLassoResult """ key = vcov_key(vcov) if key not in ("iid", "hetero") and not key.startswith("CRV1:"): raise ValueError("vcov must be 'iid', 'hetero' or {'CRV1': column}") cluster = _cluster(key) if key != "hetero" else None robust = key != "iid" needs_folds = penalty in _fit.CV_RULES or node_penalty in _fit.CV_RULES design = _design.build(fml, data, unpenalized=unpenalized, weights=weights, weights_type=weights_type, n_folds=n_folds if needs_folds else None, fold_by=fold_by, seed=seed, save_rows=robust or penalty == "rigorous", carry=cluster or [], options=options) names, cp = design.names, design.cp main = fit_nuisance(sub_design(design, design.depvar, names, design.unpenalized), penalty=penalty, standardize=standardize, tol=tol) m = moments(cp.total(), cp.sums.sum(axis=0), cp.weight_sums.sum(), int(cp.counts.sum()), standardize=False) targets = list(names) if coefficients is None else list(coefficients) missing = [t for t in targets if t not in names] if missing: raise ValueError(f"coefficients {missing} are not covariates of the model") dropped = [t for t in targets if not m.usable[names.index(t)]] if dropped: warnings.warn(f"no variation left after the fixed effects in {dropped}; they are " "not debiased", stacklevel=2) targets = [t for t in targets if t not in dropped] jt = [names.index(t) for t in targets] def node(j): others = [n for i, n in enumerate(names) if i != j] nu = fit_nuisance(sub_design(design, names[j], others), penalty=node_penalty, standardize=standardize, tol=tol) z = np.zeros(len(names)) z[j] = 1.0 z[[i for i in range(len(names)) if i != j]] = -nu.beta return z, nu.penalty # the nodewise lassos run in parallel, so BLAS gets one thread with single_blas(), ThreadPoolExecutor(max_workers=n_threads or 8) as ex: nodes = list(ex.map(node, jt)) Z = np.column_stack([z for z, _ in nodes]) # (k, T) scale = np.array([Z[:, t] @ m.C[:, j] for t, j in enumerate(jt)]) Zt = Z / scale beta = main.beta r = m.c - m.C @ beta # cov(x, residual) bhat = beta[jt] + Zt.T @ r W, N = m.W, cp.n_obs rss = W * (m.var_y - 2 * beta @ m.c + beta @ m.C @ beta) nnz = int(np.sum(beta != 0)) + (0 if design.fe else 1) + cp.k_fe sigma = float(np.sqrt(max(rss, 0.0) / max(N - nnz, 1))) n_clusters = {} if not robust: V = sigma ** 2 * (Zt.T @ m.C @ Zt) / W else: weight = cp.weight_column cols = [design.depvar, *names] + ([weight] if weight else []) + (cluster or []) acc = ScoreMeat(len(jt), cluster) mean_y, mean_x = m.mean[0], m.mean[1:] s_bar = (W / N) * (Zt.T @ r) # the scores' mean, from the moments for b in iter_rows(cp, cols): Xc = np.column_stack([b[n] for n in names]) - mean_x e = b[design.depvar] - mean_y - Xc @ beta w = b[weight] if weight else 1.0 acc.add((w * e)[:, None] * (Xc @ Zt) - s_bar, {c: b[c] for c in cluster} if cluster else None) meat = acc.meat() if cluster: G = acc.n_clusters meat = meat * G / max(G - 1, 1) n_clusters[key.split(":", 1)[1]] = G V = meat / W ** 2 cp.cleanup() return DebiasedLassoResult( fml=fml, depvar=design.depvar, coefnames=targets, beta=bhat, vcov=V, vcov_type=key, df_t=max(N - nnz, 1), n_obs=N, all_vcovs={key: (V, max(N - nnz, 1))}, n_clusters=n_clusters, collin_vars=dropped, weights=weights, weights_type=weights_type, diagnostics={"rows_saved": robust, "n_folds": n_folds if needs_folds else None}, lasso=dict(zip(names, map(float, beta), strict=True)), penalty=main.penalty, penalty_rule=str(penalty), node_penalties=dict(zip(targets, (p for _, p in nodes), strict=True)), sigma=sigma, nodewise=Zt, fe_names=list(design.fe), covariates=list(names))