Source code for penalized_stream.logit

"""The penalized logit, probit and Poisson model, with no absorbed fixed
effect or one, on hdfe-stream's Newton passes (`hdfe_stream.core.newton`):
`lasso_logit_stream`, `elastic_net_logit_stream` and their probit and Poisson
counterparts."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any

import numpy as np
import polars as pl
from hdfe_stream.core.resources import thread_scope
from hdfe_stream.core.utils import as_lazy
from scipy.stats import norm

from . import _fit, _logit
from ._folds import FOLD
from .results import PenalizedResult


[docs] @dataclass(repr=False) class PenalizedLogitResult(PenalizedResult): """A penalized logit, probit or Poisson model along a path of penalties, and the penalty chosen on it. As `PenalizedResult`, with the cross-validated error the mean deviance (per unit of weight) of the held-out rows -- for the logit and probit -2 log-likelihood, for Poisson twice the excess of the saturated model's log-likelihood, as glmnet's -- and: Attributes ---------- family : str ``"logit"``, ``"probit"`` or ``"poisson"``. effects : numpy.ndarray The group effects at the chosen penalty (the intercept, alone, with no fixed effect). fe_levels : polars.DataFrame or None The fixed effect's groups (its columns), in the order of `effects`. deviance : numpy.ndarray The full-sample fit's deviance along the path. """ effects: Any = None fe_levels: Any = None deviance: Any = None family: str = "logit" _source: Any = None cv_measure = "deviance" @property def method(self) -> str: return (("Lasso " if self.l1_ratio == 1.0 else "Elastic net ") + {"logit": "logit", "probit": "probit", "poisson": "Poisson"}[self.family])
[docs] def fixef(self) -> pl.DataFrame: """The fixed effect's estimated group effects at the chosen penalty.""" if not self.fe_names: raise ValueError("the model has no fixed effect") return self.fe_levels.with_columns(pl.Series("effect", self.effects))
[docs] def predict(self, newdata=None, which=None, type: str = "response") -> pl.LazyFrame: """`newdata` (by default the data fitted), lazily, with ``xb`` (the linear predictor, the group's effect included) and with ``type="response"`` the mean: ``probability`` for the logit and probit, ``mean`` for Poisson. With a fixed effect, a row of a group not in the fit gets nulls; only the chosen penalty's effects are kept, so `which` must be the chosen one.""" if type not in ("response", "link"): raise ValueError("type must be 'response' or 'link'") i = self._index(which) frame = as_lazy(self._source if newdata is None else newdata) if FOLD in frame.collect_schema(): frame = frame.drop(FOLD) terms = [float(b) * self._exprs[nm] for nm, b in zip(self.coefnames, self.coef_path[i], strict=True) if b != 0.0] if self.fe_names: if i != self.index: raise ValueError("with a fixed effect, predictions are at the chosen penalty") cols = self.fe_levels.columns eff = "__ps_effect" frame = frame.join(self.fe_levels.with_columns( pl.Series(eff, self.effects)).lazy(), on=cols, how="left", maintain_order="left") base = pl.col(eff) else: base = pl.lit(float(self.intercept_path[i])) xb = pl.sum_horizontal([base, *terms]) if terms else base if self.fe_names: xb = pl.when(pl.col(eff).is_null()).then(None).otherwise(xb) frame = frame.with_columns(xb.cast(pl.Float64).alias("xb")) if type == "response": xb = pl.col("xb") if self.family == "logit": frame = frame.with_columns((1.0 / (1.0 + (-xb).exp())).alias("probability")) elif self.family == "probit": frame = frame.with_columns(xb.map_batches( lambda v: pl.Series(norm.cdf(v.to_numpy())), return_dtype=pl.Float64, is_elementwise=True).alias("probability")) else: frame = frame.with_columns(xb.exp().alias("mean")) return frame.drop(eff, strict=False) if self.fe_names else frame
[docs] def sample(self, check: bool = True): raise NotImplementedError("sample() is not available for the penalized GLMs")
def summary_dict(self, coefficients: bool = True) -> dict: out = super().summary_dict(coefficients) out["family"] = {"logit": "binomial", "probit": "binomial (probit link)", "poisson": "poisson"}[self.family] return out
def _rigorous_lambda(n, p, c, gamma): """hdm's rlassologit penalty on glmnet's scale: lambda0 / (2n), lambda0 = c/2 sqrt(n) qnorm(1 - gamma / (2p)).""" return float(c * norm.ppf(1.0 - gamma / (2.0 * p)) / (4.0 * np.sqrt(n))) SOLVERS = ("auto", "in_memory", "streaming") def _choose_solver(solver, model, n_folds, options): """`solver`, with ``"auto"`` the in-memory solver when its rows fit the memory budget (``max_memory_gb``, else the machine's available memory) and it should be the faster (`_inmemory_glm.prefers_in_memory`: a wide design, or at most 200,000 rows), else the streamed one.""" if solver != "auto": return solver from hdfe_stream.core.resources import MemoryBudget from ._inmemory_glm import memory_gb, prefers_in_memory n_models = 1 + (n_folds or 0) budget = MemoryBudget(options.get("max_memory_gb"), options.get("memory_reserve")) fast = prefers_in_memory(model.ld) return "in_memory" if fast and budget.fits(memory_gb(model.ld, n_models)) else "streaming" def _run(fml, data, *, l1_ratio, penalty, unpenalized, weights, weights_type, n_folds, fold_by, seed, n_lambdas, lambda_min_ratio, standardize, tol, rigorous_options, options, family="logit", solver="auto"): if not 0.0 <= l1_ratio <= 1.0: raise ValueError("l1_ratio must be between 0 and 1") if solver not in SOLVERS: raise ValueError(f"solver must be one of {SOLVERS}; got {solver!r}") needs_cv = penalty in _fit.CV_RULES rigorous = penalty == "rigorous" if rigorous and l1_ratio != 1.0: raise ValueError("penalty='rigorous' is a lasso penalty (l1_ratio=1)") if rigorous and family != "logit": raise ValueError("penalty='rigorous' is the logit's plug-in penalty; for the " f"{family} use 'cv', a criterion or a value") if not rigorous and not needs_cv and not ( penalty in _fit.CRITERIA or (isinstance(penalty, (int, float)) and not isinstance(penalty, bool))): raise ValueError(f"penalty must be a number, 'cv', 'cv_1se', 'rigorous' or one of " f"{_fit.CRITERIA}; got {penalty!r}") options = dict(options) n_threads = options.pop("n_threads", None) folds = n_folds if needs_cv else None with thread_scope(n_threads): model = _logit.build(fml, data, unpenalized=unpenalized, weights=weights, weights_type=weights_type, n_folds=folds, fold_by=fold_by, seed=seed, options=options, family=family) try: chosen = _choose_solver(solver, model, folds, options) info = {"solver": chosen} value = penalty if rigorous: ro = dict(rigorous_options or {}) unknown = sorted(set(ro) - {"c", "gamma"}) if unknown: raise TypeError(f"unknown rigorous_options for the logit: {unknown}") n = model.ld.n_obs p = len([nm for nm in model.names if nm not in model.unpenalized]) c = float(ro.get("c", 1.1)) gamma = float(ro.get("gamma", 0.1 / np.log(n))) value = _rigorous_lambda(n, p, c, gamma) info = {"rigorous": {"c": c, "gamma": gamma, "lambda0_hdm": value * 2 * n}} path = _logit.fit_path(model, l1_ratio=l1_ratio, penalty=value, n_lambdas=n_lambdas, lambda_min_ratio=lambda_min_ratio, standardize=standardize, tol=tol, cv=needs_cv, keep_effects_path=model.ld.n_groups * n_lambdas <= 5_000_000, solver=chosen) if rigorous: index, rule = len(path.lambdas) - 1, "rigorous" else: index, rule = _fit.choose(path, penalty) effects = (path.effects_path[index] if path.effects_path is not None else path.effects) if path.effects_path is None and index != len(path.lambdas) - 1: # the effects kept are the last penalty's; refit at the chosen one again = _logit.fit_path(model, l1_ratio=l1_ratio, penalty=float(path.lambdas[index]), n_lambdas=n_lambdas, lambda_min_ratio=None, standardize=standardize, tol=tol, cv=False, solver=chosen) effects = again.effects info["effects_refit_passes"] = again.timings["passes"] finally: ld = model.ld ld.cleanup() diag = {**ld.diagnostics, **path.timings, **info, "scale": path.scale, "separation": ld.separation} return PenalizedLogitResult( formula=fml, depvar=model.depvar, coefnames=list(model.names), unpenalized=list(model.unpenalized), fe_names=list(model.fe), l1_ratio=float(l1_ratio), lambdas=path.lambdas, coef_path=path.coef, intercept_path=path.intercept, penalty=float(path.lambdas[index]), penalty_rule=rule, index=int(index), cv_mean=path.cv_mean, cv_se=path.cv_se, n_folds=folds, fold_by=model.fold_by, criteria=path.criteria, df=path.df, n_obs=ld.n_obs, k_fe=ld.n_groups if model.fe else 0, n_levels={model.fe[0]: ld.n_groups} if model.fe else {}, dropped=path.dropped, weights=weights, weights_type=weights_type, diagnostics=diag, _exprs=model.exprs, effects=np.asarray(effects), fe_levels=ld.fe_levels, deviance=path.deviance, family=family, _source=data) _DOC = """ Minimizes ``-(1/W) sum_i w_i loglik_i + penalty * {form}`` over standardized covariates, W the sum of the weights: glmnet's {objective} objective. The intercept, or with one absorbed fixed effect each group's effect, is not penalized. The data are stored once, by hdfe-stream. With the streamed solver each Newton step is one read of them, shared by the cross-validation's models, and a path takes a few reads per penalty; the in-memory solver (`solver`) holds them in memory instead. Parameters ---------- fml : str ``"y ~ x1 + x2 + i(region)"`` or ``"y ~ x1 + x2 | firm"``: {outcome}, the covariates (penalized) and at most one fixed effect. Groups of the fixed effect whose effects would be infinite ({infinite}) are dropped. data : str, Path, polars.LazyFrame or polars.DataFrame penalty : str or float, default "cv" ``"cv"`` (the smallest cross-validated deviance, lambda_min), ``"cv_1se"``, an information criterion (``"aic"``, ``"bic"``, ``"ebic"``, ``"aicc"``, from the deviance){rigorous}, or a value. unpenalized : str or list of str, optional Covariates left unpenalized, as for `lasso_stream`. weights : str, optional Analytic (or, with ``weights_type="fweights"``, frequency) weights. n_folds : int, default 5 fold_by : str, optional ``"rows"`` (the default) or a column whose values make the folds. Not the fixed effect: a held-out group would have no estimated effect. A group whose effect would be infinite in a fold's training rows (or that has none) is left out of that fold's model, and its held-out rows out of that fold's deviance. seed : int, default 0 n_lambdas : int, default 100 lambda_min_ratio : float, optional Default 1e-4 with more rows than covariates, else 1e-2 (glmnet's). standardize : bool, default True Penalize the covariates as if scaled to unit variance, by their standard deviation over each model's rows (glmnet's; with a fixed effect too, not the within-group deviation). tol : float, default 1e-7 Convergence of each penalty's Newton steps: the largest change in a coefficient, squared and weighted by its information. solver : {{"auto", "in_memory", "streaming"}}, default "auto" How each penalty's fit is computed. ``"in_memory"`` holds the rows in memory and fits by coordinate descent over them; ``"streaming"`` reads the stored rows once per Newton step and needs memory only for the information matrices. ``"auto"`` uses the in-memory solver when the rows fit within ``max_memory_gb`` (else the machine's available memory) and either the design has at least 512 covariates (where the streamed solver's information matrices are costly: with about 1,000 indicator columns the in-memory solver was 17 to 130 times faster from 10,000 rows to 100,000) or there are at most 200,000 rows. Otherwise it streams. On narrow designs the solvers cross over at about 400,000 to 500,000 rows on an 8-core laptop and 150,000 to 200,000 on a 16-vCPU server; between those, setting the solver can be faster than ``"auto"``. **options Options for the stored rows: ``workdir``, ``storage``, ``dtype``, ``block_mb``, ``chunk_mb``, ``max_memory_gb``, ``verbose``; and ``n_threads``. Returns ------- PenalizedLogitResult """ _RIGOROUS = (", ``\"rigorous\"`` (Belloni, Chernozhukov and Wei's plug-in penalty, as " "hdm's rlassologit: c qnorm(1 - gamma / (2p)) / (4 sqrt(n)); " "``rigorous_options`` sets ``c`` (1.1) and ``gamma`` (0.1 / log n))") _FAMILY_DOC = { "logit": dict(name="logit", objective="binomial", outcome="a 0/1 outcome", infinite="an outcome that never varies"), "probit": dict(name="probit", objective="binomial, with the probit link in place of the logit,", outcome="a 0/1 outcome", infinite="an outcome that never varies"), "poisson": dict(name="Poisson model", objective="Poisson", outcome="a nonnegative outcome (a count)", infinite="an outcome that is always zero"), } def _lasso(family): def fit(fml: str, data: Any, *, penalty: str | float = "cv", unpenalized=None, weights=None, weights_type: str = "aweights", n_folds: int = 5, fold_by: str | None = None, seed: int = 0, n_lambdas: int = 100, lambda_min_ratio: float | None = None, standardize: bool = True, tol: float = 1e-7, rigorous_options: dict | None = None, solver: str = "auto", **options) -> PenalizedLogitResult: return _run(fml, data, l1_ratio=1.0, penalty=penalty, unpenalized=unpenalized, weights=weights, weights_type=weights_type, n_folds=n_folds, fold_by=fold_by, seed=seed, n_lambdas=n_lambdas, lambda_min_ratio=lambda_min_ratio, standardize=standardize, tol=tol, rigorous_options=rigorous_options, options=options, family=family, solver=solver) d = _FAMILY_DOC[family] fit.__name__ = fit.__qualname__ = ("lasso_poisson_stream" if family == "poisson" else f"lasso_{family}_stream") fit.__doc__ = (f"The lasso {d['name']}: an L1 penalty on the covariates.\n" + _DOC.format(form="sum_j |b_j|", objective=d["objective"], outcome=d["outcome"], infinite=d["infinite"], rigorous=_RIGOROUS if family == "logit" else "") + (""" rigorous_options : dict, optional With ``penalty="rigorous"``: ``c`` and ``gamma``. """ if family == "logit" else "")) return fit def _elastic_net(family): def fit(fml: str, data: Any, *, l1_ratio: float = 0.5, penalty: str | float = "cv", unpenalized=None, weights=None, weights_type: str = "aweights", n_folds: int = 5, fold_by: str | None = None, seed: int = 0, n_lambdas: int = 100, lambda_min_ratio: float | None = None, standardize: bool = True, tol: float = 1e-7, solver: str = "auto", **options) -> PenalizedLogitResult: return _run(fml, data, l1_ratio=float(l1_ratio), penalty=penalty, unpenalized=unpenalized, weights=weights, weights_type=weights_type, n_folds=n_folds, fold_by=fold_by, seed=seed, n_lambdas=n_lambdas, lambda_min_ratio=lambda_min_ratio, standardize=standardize, tol=tol, rigorous_options=None, options=options, family=family, solver=solver) d = _FAMILY_DOC[family] fit.__name__ = fit.__qualname__ = ("elastic_net_poisson_stream" if family == "poisson" else f"elastic_net_{family}_stream") fit.__doc__ = (f"The elastic-net {d['name']}: a mix of L1 and L2 penalties.\n" + _DOC.format(form="sum_j (l1_ratio |b_j| + (1 - l1_ratio)/2 b_j^2)", objective=d["objective"], outcome=d["outcome"], infinite=d["infinite"], rigorous="") + """ l1_ratio : float, default 0.5 The L1 share of the penalty (glmnet's alpha): 1 is the lasso. """) return fit lasso_logit_stream = _lasso("logit") elastic_net_logit_stream = _elastic_net("logit") lasso_probit_stream = _lasso("probit") elastic_net_probit_stream = _elastic_net("probit") lasso_poisson_stream = _lasso("poisson") elastic_net_poisson_stream = _elastic_net("poisson")