"""Post-double-selection for a binary outcome (Belloni, Chernozhukov and Wei
2016): the logit coefficient of a treatment, controlling for the controls
that a lasso logit of the outcome or a weighted lasso of the treatment
selects.
1. A lasso logit of y on the treatments (unpenalized) and the controls
selects controls I1; the logit of y on the treatments and I1 gives each
row's weight f_i^2 = w_i p_i (1 - p_i).
2. For each treatment d, a lasso of f d on f x (the controls), both centered
by their f^2-weighted means (within the fixed effect's groups, with one),
selects controls I2; the weighting is what makes the selection target
the controls that matter for the logit's score.
3. The logit of y on the treatments and the union of I1 and every I2 (and
the always-included controls) gives the estimates, with hdfe-stream's
(`feglm_stream`) standard errors.
Steps 1 and 2 use the plug-in penalties by default: hdm's rlassologit's for
the logit (c = 1.1, gamma = 0.1 / log n), and for the weighted lasso the
heteroskedastic plug-in penalty with hdm's rlassologitEffect's level, 2.2
sqrt(n) qnorm(1 - 0.05 / max(n, p log n)) in hdm's scale. Unlike hdm's
rlassologitEffect, the treatment is not penalized in step 1, the weighted
lasso's intercept (or fixed effect) is weighted too, and the final step is
the logit's own inference.
The rows are stored once (hdfe-stream's `core.newton` pass 0); the lasso
logit is a few reads of them, the weighted lasso's cross-products come from
one more (the information at step 1's refit, with the effects profiled out),
and its loadings from a copy of its weighted rows. The final logit is
hdfe-stream's `feglm_stream`, so its result reports and exports as any other.
"""
from __future__ import annotations
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import numpy as np
import polars as pl
import pyarrow as pa
import pyarrow.parquet as pq
from hdfe_stream.core.resources import thread_scope
from hdfe_stream.core.utils import as_lazy
from scipy.special import expit
from . import _design, _fit, _logit
from .double_selection import DoubleSelection
from .logit import _rigorous_lambda
# the options that go to the final logit (`feglm_stream`)
_FINAL_OPTIONS = ("workdir", "polars_engine", "max_memory_gb", "memory_reserve", "verbose",
"logger")
class _WeightedCross:
"""The weighted lasso's cross-products, as `_fit.fit` and
`rigorous_penalty` read them: one split, already centered (zero sums),
from the profiled information; and its rows, f-scaled and centered, from
a Parquet copy."""
def __init__(self, C, idx, n, path, names):
ix = np.ix_(idx, idx)
self.gram = C[ix][None]
self.sums = np.zeros((1, len(idx)))
self.weight_sums = np.array([float(n)])
self.counts = np.array([n])
self.n_obs, self.k_fe, self.n_levels = n, 0, {}
self.weight_column, self.diagnostics = None, {}
self._path, self._names = path, names
@property
def n_splits(self):
return 1
def total(self):
return self.gram[0]
def rows(self):
return pl.scan_parquet(self._path).select(self._names)
@dataclass
class _Sub:
depvar: str
names: list
unpenalized: list
fe: list
n_folds: int
cp: Any
shift: np.ndarray
weights_type: str = "aweights"
extra: dict = field(default_factory=dict)
def _refit(model, cols):
"""The unpenalized logit on the covariates `cols` (the others at zero)."""
st = _logit._Path(model, pf=np.zeros(len(model.names)), l1_ratio=1.0, standardize=False,
tol=1e-12, cv=False, max_outer=100)
st.usable = np.ones(len(model.names), bool)
cols = sorted(cols)
st.refresh([0], np.asarray(cols, dtype=np.int64))
if cols:
st.solve(0.0, cols, [0])
return st.b[0].copy(), st.a[0].copy()
def _choose(model, penalty, pf_names, tol, standardize, rigorous_options, n):
"""The lasso logit's coefficients at `penalty` (`pf_names`: unpenalized)."""
model.unpenalized = pf_names
if penalty == "rigorous":
ro = dict(rigorous_options or {})
p = len([nm for nm in model.names if nm not in pf_names])
value = _rigorous_lambda(n, p, float(ro.get("c", 1.1)),
float(ro.get("gamma", 0.1 / np.log(n))))
path = _logit.fit_path(model, l1_ratio=1.0, penalty=value, n_lambdas=100,
lambda_min_ratio=None, standardize=standardize, tol=tol,
cv=False)
return path.coef[-1], value
path = _logit.fit_path(model, l1_ratio=1.0, penalty=penalty, n_lambdas=100,
lambda_min_ratio=None, standardize=standardize, tol=tol, cv=False)
i, _ = _fit.choose(path, penalty)
return path.coef[i], float(path.lambdas[i])
[docs]
def double_selection_logit_stream(fml: str, data: Any, *, controls: str, unpenalized=None,
penalty: str | float = "rigorous", vcov="hetero",
weights=None, weights_type: str = "aweights",
standardize: bool = True, tol: float = 1e-7,
rigorous_options: dict | None = None, **options):
"""Post-double-selection for a binary outcome: the logit coefficients of
the treatments in `fml`, controlling for the controls the lassos select
(Belloni, Chernozhukov and Wei 2016; see the module docstring).
Parameters
----------
fml : str
``"y ~ d"`` or ``"y ~ d | fe"``: a 0/1 outcome, the treatment(s) and at
most one fixed effect.
data : str, Path, polars.LazyFrame or polars.DataFrame
controls : str
The candidate controls, as a right-hand side.
unpenalized : str or list of str, optional
Controls always included, as for `double_selection_stream`.
penalty : str or float, default "rigorous"
The lassos' penalty: ``"rigorous"`` (the plug-in penalties), an
information criterion (``"aic"``, ``"bic"``, ``"ebic"``, ``"aicc"``)
or a value (for both the lasso logit and the weighted lassos, on their
own scales). Cross-validation is not available here.
vcov : default "hetero"
The final logit's vcov, as for `hdfe_stream.feglm_stream`.
weights, weights_type, standardize, tol
As for `lasso_logit_stream`.
rigorous_options : dict, optional
``c`` and ``gamma`` of the lasso logit's plug-in penalty.
**options
Options for the stored rows (``workdir``, ``verbose``, ...) and
``n_threads``.
Returns
-------
hdfe_stream.HDFEResult
The final logit, with ``double_selection`` (a `DoubleSelection`).
"""
from hdfe_stream import feglm_stream
from ._rigorous import rigorous_penalty
if not isinstance(controls, str) or not controls.strip():
raise ValueError("controls must be a right-hand side, e.g. 'x1 + x2 + i(region)'")
if penalty in _fit.CV_RULES:
raise ValueError("cross-validation is not available for the logit double selection; "
"use 'rigorous', a criterion or a value")
options = dict(options)
n_threads = options.pop("n_threads", None)
lf = as_lazy(data)
spec, yname, treat, _, fe, exprs = _design.parse_model(fml, None, lf)
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")
all_exprs = {**cexprs, **exprs}
rhs = " + ".join([spec.rhs, controls]
+ ([unpenalized] if isinstance(unpenalized, str) else []))
big = f"{spec.dep} ~ {rhs}" + (f" | {spec.fe}" if spec.fe else "")
with thread_scope(n_threads):
model = _logit.build(big, data, weights=weights, weights_type=weights_type,
options=options)
try:
names = model.names
missing = [nm for nm in [*treat, *cnames] if nm not in names]
if missing:
raise ValueError(f"could not find {missing} among the compiled columns")
ld = model.ld
n = ld.n_obs
# 1: the lasso logit, the treatments unpenalized, and its refit
beta, lam1 = _choose(model, penalty, list(treat) + list(unpen), tol, standardize,
rigorous_options, n)
sel_y = [c for c in cnames if beta[names.index(c)] != 0.0 and c not in unpen]
keep = [names.index(nm) for nm in [*treat, *sel_y, *unpen]]
b, a = _refit(model, keep)
# 2: the weighted lassos, from the information at the refit
mom = ld.newton_pass(b, a)
C, _ = mom.profiled(0)
D = mom.effects_information[0]
with np.errstate(divide="ignore", invalid="ignore"):
means = np.where(D[:, None] > 0, mom.cross[0] / D[:, None], 0.0) # (G, k)
tmp = tempfile.TemporaryDirectory(prefix="ps_weighted_", dir=options.get("workdir"))
rows_path = Path(tmp.name) / "weighted_rows.parquet"
cols_out = [*treat, *cnames]
idx_out = [names.index(c) for c in cols_out]
writer = None
for X, _y, w, f, _s in ld.rows():
eta = X @ b + a[f]
p = expit(eta)
h = p * (1 - p) * (1.0 if w is None else w)
U = (X[:, idx_out] - means[f][:, idx_out]) * np.sqrt(h)[:, None]
table = pa.table({c: U[:, j] for j, c in enumerate(cols_out)})
if writer is None:
writer = pq.ParquetWriter(rows_path, table.schema)
writer.write_table(table)
if writer is not None:
writer.close()
selected = {yname: sel_y}
penalties = {yname: lam1}
q = len([c for c in cnames if c not in unpen])
for d in treat:
idx = [names.index(d)] + [names.index(c) for c in cnames]
cp = _WeightedCross(C, idx, n, rows_path, cols_out)
sub = _Sub(depvar=d, names=list(cnames), unpenalized=list(unpen), fe=[],
n_folds=1, cp=cp, shift=np.zeros(len(idx)))
if penalty == "rigorous":
gamma = 0.1 * q / max(n, q * np.log(n))
lam, loadings, _ = rigorous_penalty(sub, standardize=standardize, tol=tol,
c=1.1, gamma=gamma)
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=False)
i, _ = _fit.choose(path, penalty)
selected[d] = [c for c, v in zip(cnames, path.coef[i], strict=True)
if v != 0.0 and c not in unpen]
penalties[d] = float(path.lambdas[i])
finally:
model.ld.cleanup()
if "tmp" in locals():
tmp.cleanup()
union = [c for c in cnames if c in unpen or any(c in s for s in selected.values())]
# 3: the final logit, on the same rows (complete in every candidate)
terms = [*treat, *union]
alias = {nm: f"__ps_t{j}" for j, nm in enumerate(terms)}
usable = [all_exprs[yname].is_not_null()] + [all_exprs[nm].is_finite()
for nm in [*treat, *cnames]]
if weights:
usable.append(pl.col(weights).is_finite())
final = lf.filter(pl.all_horizontal(usable)).with_columns(
[all_exprs[nm].cast(pl.Float64).alias(alias[nm]) for nm in terms])
ffml = f"{spec.dep} ~ " + " + ".join(alias[nm] for nm in terms) + \
(f" | {spec.fe}" if spec.fe else "")
lopts = {k: v for k, v in options.items() if k in _FINAL_OPTIONS}
lopts.setdefault("verbose", False)
result = feglm_stream(ffml, final, "logit", vcov=vcov, weights=weights,
weights_type=weights_type, **lopts)
back = {v: k for k, v in alias.items()}
result.coefnames = [back.get(c, c) for c in result.coefnames]
result.fml = fml
result.double_selection = DoubleSelection(
treatments=list(treat), controls=list(cnames), unpenalized=list(unpen),
selected=selected, union=union, penalty=penalty, penalties=penalties,
loadings_cluster=None)
return result