Source code for penalized_stream.api

"""lasso_stream, elastic_net_stream and ridge_stream."""

from __future__ import annotations

from typing import Any

import numpy as np

from . import _design, _fit, _groups
from .results import PenalizedResult

CV_FIXED_EFFECTS = ("full_sample", "refit")


def _run(fml, data, *, l1_ratio, penalty, unpenalized, weights, weights_type, n_folds,
         fold_by, seed, cv_fixed_effects, n_lambdas, lambda_min_ratio, standardize, tol,
         cluster, rigorous_options, options, groups=None) -> PenalizedResult:
    if not 0.0 <= l1_ratio <= 1.0:
        raise ValueError("l1_ratio must be between 0 and 1")
    if cv_fixed_effects not in CV_FIXED_EFFECTS:
        raise ValueError(f"cv_fixed_effects must be one of {CV_FIXED_EFFECTS}")
    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 groups is not None and rigorous:
        raise ValueError("groups= is not available with penalty='rigorous' (the plug-in "
                         "penalty is for single coefficients)")
    if cluster is not None and not rigorous:
        raise ValueError("cluster= sets the rigorous penalty's loadings; it needs "
                         "penalty='rigorous'")
    folds = n_folds if needs_cv else None
    carry = [] if cluster is None else [c.strip() for c in cluster.split("^")]
    design = _design.build(fml, data, unpenalized=unpenalized, weights=weights,
                           weights_type=weights_type, n_folds=folds, fold_by=fold_by,
                           seed=seed, save_rows=rigorous, carry=carry, options=options)
    group_labels, group_ids = _groups.assign(design.names, groups, design.unpenalized)
    gids = group_ids if groups is not None else None
    loadings = None
    if rigorous:
        from ._rigorous import rigorous_penalty
        lam, loadings, info = rigorous_penalty(design, cluster=carry or None,
                                               standardize=standardize, tol=tol,
                                               **(rigorous_options or {}))
        path = _fit.fit(design, l1_ratio=1.0, penalty=lam, n_lambdas=n_lambdas,
                        lambda_min_ratio=lambda_min_ratio, standardize=standardize, tol=tol,
                        loadings=loadings, cv=False)
        index, rule = len(path.lambdas) - 1, "rigorous"
        design.cp.cleanup()
    else:
        info = {}
        if needs_cv and cv_fixed_effects == "refit" and len(design.fe) > 1:
            from ._exact import refit_cv
            path = _fit.fit(design, l1_ratio=l1_ratio, penalty=penalty, n_lambdas=n_lambdas,
                            lambda_min_ratio=lambda_min_ratio, standardize=standardize,
                            tol=tol, cv=False, groups=gids)
            refit_cv(design, path, l1_ratio=l1_ratio, standardize=standardize, tol=tol,
                     options=options, groups=gids)
        else:
            path = _fit.fit(design, l1_ratio=l1_ratio, penalty=penalty, n_lambdas=n_lambdas,
                            lambda_min_ratio=lambda_min_ratio, standardize=standardize,
                            tol=tol, groups=gids)
        index, rule = _fit.choose(path, penalty)
    cp = design.cp
    m = _fit.full_moments(cp, standardize)
    diag = {**cp.diagnostics, **path.timings, **info, "scale": m.scale}
    exact_needed = needs_cv and len(design.fe) > 1
    return PenalizedResult(
        formula=fml, depvar=design.depvar, coefnames=list(design.names),
        unpenalized=list(design.unpenalized), fe_names=list(design.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=design.fold_by, criteria=path.criteria, df=path.df,
        n_obs=cp.n_obs, k_fe=cp.k_fe, n_levels=dict(cp.n_levels), dropped=path.dropped,
        weights=weights, weights_type=weights_type,
        cv_fixed_effects=(cv_fixed_effects if exact_needed else None),
        loadings=None if loadings is None else np.asarray(loadings),
        groups=(dict(zip(design.names, group_labels, strict=True)) if groups is not None
                else None),
        diagnostics=diag, _exprs=design.exprs, _cp=cp)


_DOC_COMMON = """
    Parameters
    ----------
    fml : str
        A pyfixest formula, ``"y ~ x1 + x2 + i(region) | worker + firm"``: the
        covariates are penalized; the fixed effects after ``|`` are partialled
        out (never penalized). One model; no instruments or varying slopes.
    data : str, Path, polars.LazyFrame or polars.DataFrame
        A Parquet path or glob, a LazyFrame or a DataFrame.
    penalty : str or float, default "cv"
        How to choose the penalty: ``"cv"`` (the one with the smallest
        cross-validated mean squared error, lambda_min), ``"cv_1se"`` (the
        largest within one standard error of it, lambda_1se), an information
        criterion (``"aic"``, ``"bic"``, ``"ebic"``, ``"aicc"``){rigorous}, or a
        value.
    unpenalized : str or list of str, optional
        Covariates left unpenalized: a right-hand side (``"age + i(year)"``,
        added to the model) or names of the formula's covariates.{groups}
    weights : str or polars.Expr, optional
        Analytic (or, with ``weights_type="fweights"``, frequency) weights.
    n_folds : int, default 5
        Folds for cross-validation (used by ``penalty="cv"`` and ``"cv_1se"``).
    fold_by : str, optional
        What the folds are made of: ``"rows"`` (each row hashed by its position)
        or a column (each value's rows in one fold). Default: the groups of the
        fixed effect with the most levels (the one hdfe-stream streams), or rows
        without fixed effects. With one fixed effect, folds of its groups make
        the cross-validation exact.
    seed : int, default 0
        Seed of the fold assignment.
    cv_fixed_effects : {{"full_sample", "refit"}}, default "full_sample"
        With more than one fixed effect: ``"full_sample"`` partials them out
        once, from all the rows, so each fold's held-out rows are residualized
        with effects their own outcomes helped estimate (one pass);
        ``"refit"`` estimates them again on each fold's training rows (exact,
        8 to 15 times the time in simulations). The two choose the same
        penalty or a neighboring one, with the same prediction error; but with
        small cells in every dimension the default's cross-validated error
        can be 10% or more below the out-of-sample error, so use ``"refit"``
        when that number itself matters. See docs/fixed_effects_cv.md.
    n_lambdas : int, default 100
    lambda_min_ratio : float, optional
        The smallest penalty of the path as a share of the largest; default
        1e-4 when there are more rows than covariates, else 1e-2 (glmnet's).
    standardize : bool, default True
        Penalize the covariates as if scaled to unit variance (the
        coefficients are reported on their own scale).
    tol : float, default 1e-7
        Convergence tolerance of the coordinate descent (glmnet's).
    **options
        hdfe-stream's options: ``workdir``, ``n_threads``, ``max_memory_gb``,
        ``fixef_rm``, ``connected``, ``stream``, ``verbose``, ...

    Returns
    -------
    PenalizedResult
"""

_GROUPS = """
    groups : "factors" or dict, optional
        Keep or drop covariates together (the group lasso; grpreg's): with
        ``"factors"`` each factor's indicators (``C(x)``, ``i(x)``, a string
        column, an interaction of factors) are one group and every other
        covariate is a group of its own; a dict ``{name: [covariates]}`` names
        the groups. Each group is orthonormalized and penalized by the norm of
        its coefficients times the square root of its size, so a factor's
        selection does not depend on its reference level (and ``standardize``
        has no effect). Not with ``penalty="rigorous"``."""

_RIGOROUS = ("""
    cluster : str, optional
        With ``penalty="rigorous"``: cluster-robust penalty loadings, by this
        column (``"a^b"`` for a combination).
    rigorous_options : dict, optional
        With ``penalty="rigorous"``: ``c`` (1.1), ``gamma`` (0.1 / log n),
        ``max_iter`` (15), ``loadings_tol`` (1e-5), ``homoskedastic`` (False).
""")


[docs] def lasso_stream(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, cv_fixed_effects: str = "full_sample", n_lambdas: int = 100, lambda_min_ratio: float | None = None, standardize: bool = True, tol: float = 1e-7, groups=None, cluster: str | None = None, rigorous_options: dict | None = None, **options) -> PenalizedResult: 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, cv_fixed_effects=cv_fixed_effects, n_lambdas=n_lambdas, lambda_min_ratio=lambda_min_ratio, standardize=standardize, tol=tol, cluster=cluster, rigorous_options=rigorous_options, options=options, groups=groups)
[docs] def elastic_net_stream(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, cv_fixed_effects: str = "full_sample", n_lambdas: int = 100, lambda_min_ratio: float | None = None, standardize: bool = True, tol: float = 1e-7, groups=None, **options) -> PenalizedResult: 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, cv_fixed_effects=cv_fixed_effects, n_lambdas=n_lambdas, lambda_min_ratio=lambda_min_ratio, standardize=standardize, tol=tol, cluster=None, rigorous_options=None, options=options, groups=groups)
[docs] def ridge_stream(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, cv_fixed_effects: str = "full_sample", n_lambdas: int = 100, lambda_min_ratio: float | None = None, standardize: bool = True, **options) -> PenalizedResult: return _run(fml, data, l1_ratio=0.0, penalty=penalty, unpenalized=unpenalized, weights=weights, weights_type=weights_type, n_folds=n_folds, fold_by=fold_by, seed=seed, cv_fixed_effects=cv_fixed_effects, n_lambdas=n_lambdas, lambda_min_ratio=lambda_min_ratio, standardize=standardize, tol=1e-7, cluster=None, rigorous_options=None, options=options)
lasso_stream.__doc__ = ("""Lasso: least squares with an L1 penalty on the covariates, from one pass over the data (two or more for ``penalty="rigorous"``). Minimizes ``1/(2W) sum_i w_i (y_i - b0 - x_i'b)^2 + penalty * sum_j |b_j|`` over standardized covariates, W the sum of the weights, after the fixed effects are partialled out: glmnet's and scikit-learn's lasso. """ + _DOC_COMMON.format(rigorous=", ``\"rigorous\"`` (Belloni, Chen, Chernozhukov " "and Hansen's plug-in penalty, as hdm's rlasso)", groups=_GROUPS) + _RIGOROUS) elastic_net_stream.__doc__ = ("""Elastic net: least squares with a mix of L1 and L2 penalties on the covariates, from one pass over the data. Minimizes ``1/(2W) sum_i w_i (y_i - b0 - x_i'b)^2 + penalty * sum_j (l1_ratio |b_j| + (1 - l1_ratio)/2 b_j^2)`` over standardized covariates: scikit-learn's ElasticNet. glmnet's elastic net (alpha = l1_ratio) differs unless the outcome's standard deviation is 1. l1_ratio : float, default 0.5 The L1 share of the penalty: 1 is the lasso, 0 ridge. """ + _DOC_COMMON.format(rigorous="", groups=_GROUPS)) ridge_stream.__doc__ = ("""Ridge regression: least squares with an L2 penalty on the covariates, from one pass over the data, solved exactly at each penalty. Minimizes 1/(2W) sum_i w_i (y_i - b0 - x_i'b)^2 + penalty/2 * sum_j b_j^2 over standardized covariates. The default path starts at glmnet's largest ridge penalty (1000 times the lasso's). """ + _DOC_COMMON.format(rigorous="", groups=""))