"""The penalized multinomial logit and ordered logit and probit, with no
absorbed fixed effect or one, on logit-stream's Newton passes
(`logit_stream.core`): `lasso_mlogit_stream`,
`lasso_ologit_stream`, `lasso_oprobit_stream` and their
elastic-net counterparts. They need logit-stream (the ``logit`` extra)."""
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 . import _categorical, _fit
from ._folds import FOLD
from .results import PenalizedResult
def _label(v) -> str:
return str(v)
[docs]
@dataclass(repr=False)
class PenalizedCategoricalResult(PenalizedResult):
"""A penalized multinomial logit, or ordered logit or probit, along a
path of penalties, and the penalty chosen on it. As `PenalizedResult`,
with the cross-validated error the mean deviance (-2 log-likelihood per
unit of weight) of the held-out rows, and:
The coefficients (`coefnames`, `coef_path`) are, for the multinomial
logit, one per outcome level and covariate, named ``"<level>:<covariate>"``
(glmnet's symmetric form: only their differences between levels enter the
probabilities, and the penalty identifies them; an unpenalized covariate's
are centered to sum to zero over the levels, as are the intercepts). For
the ordered model, one per covariate, with P(y <= j) = F(cut_j - x'b) (a
positive coefficient moves the outcome up); the cutpoints are in
`cutpoints_path`.
Attributes
----------
model : str
``"multinomial"`` or ``"ordered"``.
link : str
``"logit"`` or ``"probit"`` (the ordered model's).
grouped : bool
Whether the multinomial logit's penalty is grouped: each covariate's
coefficients for every level enter or leave together (then they are
unique and sum to zero over the levels).
levels : list
The outcome's levels, in order.
intercept_path : numpy.ndarray
The multinomial logit's intercepts, shape (n_lambdas, J), without a
fixed effect; zeros otherwise (and for the ordered model).
cutnames : list of str
The ordered model's cutpoints (``"cut1"``, ...; with a fixed effect
the first is 0, absorbed by the effects, and not listed).
cutpoints_path : numpy.ndarray or None
Their values along the path, shape (n_lambdas, len(cutnames)).
effects : numpy.ndarray or None
The fixed effect's group effects at the chosen penalty: shape (G, J)
for the multinomial logit (each level's, -inf for a level the group
never has), (G,) for the ordered model (its location).
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 (-2 log-likelihood) along the path.
cv_folds : numpy.ndarray or None
Each fold's held-out mean deviance along the path, shape (n_folds,
n_lambdas).
"""
model: str = "multinomial"
link: str = "logit"
grouped: bool = False
levels: Any = None
covariates: Any = None
cutnames: Any = None
cutpoints_path: Any = None
effects: Any = None
fe_levels: Any = None
deviance: Any = None
cv_folds: Any = None
_source: Any = None
cv_measure = "deviance"
@property
def method(self) -> str:
kind = ("multinomial logit" if self.model == "multinomial"
else f"ordered {self.link}")
if self.grouped:
kind += " (grouped)"
return ("Lasso " if self.l1_ratio == 1.0 else "Elastic net ") + kind
# ------------------------------------------------------- coefficients
def _intercepts(self, i) -> dict:
if self.model != "multinomial" or self.fe_names:
return {}
return {f"{_label(lv)}:Intercept": float(v)
for lv, v in zip(self.levels, self.intercept_path[i], strict=True)}
def _cuts(self, i) -> dict:
if self.model != "ordered":
return {}
return {nm: float(v) for nm, v in zip(self.cutnames, self.cutpoints_path[i],
strict=True)}
[docs]
def coef(self, which=None) -> dict:
"""``{name: coefficient}`` at the chosen penalty (or at `which`), with
the multinomial logit's intercepts first (``"<level>:Intercept"``,
without a fixed effect) and the ordered model's cutpoints last."""
i = self._index(which)
out = self._intercepts(i)
out.update({nm: float(b) for nm, b in zip(self.coefnames, self.coef_path[i],
strict=True)})
out.update(self._cuts(i))
return out
[docs]
def tidy(self, which=None) -> pl.DataFrame:
"""One row per coefficient: ``term``, ``estimate``, ``penalized`` (the
intercepts and cutpoints are not)."""
i = self._index(which)
c = self.coef(i)
pen = {nm: nm not in self.unpenalized for nm in self.coefnames}
return pl.DataFrame({"term": list(c), "estimate": list(c.values()),
"penalized": [pen.get(t, False) for t in c]})
[docs]
def fixef(self) -> pl.DataFrame:
"""The fixed effect's estimated group effects at the chosen penalty:
``effect`` (the ordered model's location) or one ``effect_<level>``
column per outcome level (the multinomial logit)."""
if not self.fe_names:
raise ValueError("the model has no fixed effect")
if self.model == "ordered":
return self.fe_levels.with_columns(pl.Series("effect", np.ravel(self.effects)))
return self.fe_levels.with_columns([
pl.Series(f"effect_{_label(lv)}", self.effects[:, j])
for j, lv in enumerate(self.levels)])
# ---------------------------------------------------------- prediction
[docs]
def predict(self, newdata=None, which=None, type: str = "response") -> pl.LazyFrame:
"""`newdata` (by default the data fitted), lazily, with the linear
predictors and, with ``type="response"``, each outcome level's
probability, ``probability_<level>``.
The multinomial logit's linear predictors are ``xb_<level>`` (the
intercept or the group's effect included); the ordered model's is
``xb`` (x'b, plus the group's effect). 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)
if self.fe_names and i != self.index:
raise ValueError("with a fixed effect, predictions are at the chosen penalty")
coef = dict(zip(self.coefnames, self.coef_path[i], strict=True))
labels = [_label(lv) for lv in self.levels]
tmp = []
if self.fe_names:
cols = self.fe_levels.columns
if self.model == "ordered":
eff = {"__ps_effect": np.ravel(self.effects)}
else:
eff = {f"__ps_effect_{j}": self.effects[:, j] for j in range(len(labels))}
tmp = list(eff)
frame = frame.join(self.fe_levels.with_columns(
[pl.Series(n, v) for n, v in eff.items()]).lazy(), on=cols, how="left",
maintain_order="left")
missing = pl.col(tmp[0]).is_null() if tmp else None
def linear(prefix, base):
terms = [float(coef[f"{prefix}{nm}"]) * self._exprs[nm] for nm in self.covariates
if coef[f"{prefix}{nm}"] != 0.0]
xb = pl.sum_horizontal([base, *terms]) if terms else base
if missing is not None:
xb = pl.when(missing).then(None).otherwise(xb)
return xb.cast(pl.Float64)
if self.model == "multinomial":
names = []
for j, lab in enumerate(labels):
base = (pl.col(f"__ps_effect_{j}") if self.fe_names
else pl.lit(float(self.intercept_path[i, j])))
names.append(f"xb_{lab}")
frame = frame.with_columns(linear(f"{lab}:", base).alias(names[-1]))
if type == "response":
top = pl.max_horizontal([pl.col(n) for n in names])
ex = [(pl.col(n) - top).exp() for n in names]
tot = pl.sum_horizontal(ex)
frame = frame.with_columns([(e / tot).alias(f"probability_{lab}")
for e, lab in zip(ex, labels, strict=True)])
else:
base = pl.col("__ps_effect") if self.fe_names else pl.lit(0.0)
frame = frame.with_columns(linear("", base).alias("xb"))
if type == "response":
cuts = list(self.cutpoints_path[i])
if self.fe_names:
cuts = [0.0, *cuts]
cdf = self._cdf()
cum = [cdf(pl.lit(float(c)) - pl.col("xb")) for c in cuts]
probs = [cum[0]] + [cum[j] - cum[j - 1] for j in range(1, len(cum))] \
+ [1.0 - cum[-1]]
frame = frame.with_columns([p.alias(f"probability_{lab}")
for p, lab in zip(probs, labels, strict=True)])
return frame.drop(tmp) if tmp else frame
def _cdf(self):
if self.link == "logit":
return lambda z: 1.0 / (1.0 + (-z).exp())
from scipy.stats import norm
return lambda z: z.map_batches(lambda v: pl.Series(norm.cdf(v.to_numpy())),
return_dtype=pl.Float64, is_elementwise=True)
[docs]
def sample(self, check: bool = True):
raise NotImplementedError("sample() is not available for the penalized "
"multinomial and ordered models")
def summary_dict(self, coefficients: bool = True) -> dict:
out = super().summary_dict(coefficients)
out["model"] = self.model
out["link"] = self.link
out["levels"] = [_label(v) for v in self.levels]
return out
[docs]
def plot_path(self, ax=None, log=True):
"""The coefficients of the standardized covariates along the path
(one line per level and covariate for the multinomial logit), with
the chosen penalty marked."""
return super().plot_path(ax=ax, log=log)
def _report(model, path):
"""The path's coefficients as the result reports them: (coefnames,
coef_path, unpenalized names, intercept_path, cutnames, cutpoints_path,
scale per coefficient)."""
ld, lay = model.ld, path.layout
L = len(path.lambdas)
covs = list(model.names)
cnames = list(ld.covariates)
sd = path.scale
if model.kind == "multinomial":
J = len(ld.levels)
labels = [_label(v) for v in ld.levels]
full = np.zeros((L, J, len(cnames)))
full[:, lay.level, lay.col] = path.u
# an unpenalized column (the intercept too) is identified only up to
# a shift: center it over the levels
for c in range(len(cnames)):
if not lay.sym[lay.col == c].any():
full[:, :, c] -= full[:, :, c].mean(axis=1, keepdims=True)
keep = [cnames.index(nm) for nm in covs]
names = [f"{lab}:{nm}" for lab in labels for nm in covs]
coef = full[:, :, keep].reshape(L, -1)
unpen = [f"{lab}:{nm}" for lab in labels for nm in model.unpenalized]
ic = lay.intercept
intercept = full[:, :, ic] if ic is not None else np.zeros((L, J))
scale = np.tile(sd[keep], J)
return names, coef, unpen, intercept, None, None, scale
pc = np.asarray(ld.parameter_columns)
slope = [int(np.flatnonzero(pc == cnames.index(nm))[0]) for nm in covs]
cut = list(np.flatnonzero(pc < 0))
cutnames = [ld.names[j] for j in cut]
return (covs, path.u[:, slope], list(model.unpenalized), np.zeros(L), cutnames,
path.u[:, cut], sd[[cnames.index(nm) for nm in covs]])
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 each model's per-row state fits in the CPU's last-level cache, else
the streamed one."""
from ._inmemory import fits_cache, memory_gb
if model.kind != "multinomial":
if solver == "in_memory":
raise ValueError("solver='in_memory' is the multinomial logit's; the ordered "
"models use the streamed solver")
return "streaming"
if solver != "auto":
return solver
from hdfe_stream.core.resources import MemoryBudget
budget = MemoryBudget(options.get("max_memory_gb"), options.get("memory_reserve"))
need = memory_gb(model.ld, 1 + (n_folds or 0))
return "in_memory" if fits_cache(model.ld) and budget.fits(need) else "streaming"
def _run(fml, data, *, kind, link, levels, l1_ratio, penalty, unpenalized, weights,
weights_type, n_folds, fold_by, seed, n_lambdas, lambda_min_ratio, standardize, tol,
options, grouped=False, solver="auto"):
if not 0.0 <= l1_ratio <= 1.0:
raise ValueError("l1_ratio must be between 0 and 1")
needs_cv = penalty in _fit.CV_RULES
if penalty == "rigorous":
raise ValueError("penalty='rigorous' is the binary logit's plug-in penalty; for this "
"model use 'cv', a criterion or a value")
if 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' or one of "
f"{_fit.CRITERIA}; got {penalty!r}")
if solver not in SOLVERS:
raise ValueError(f"solver must be one of {SOLVERS}; got {solver!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 = _categorical.build(fml, data, kind=kind, link=link, levels=levels,
unpenalized=unpenalized, weights=weights,
weights_type=weights_type, n_folds=folds, fold_by=fold_by,
seed=seed, options=options)
try:
info = {}
ld = model.ld
m = len(ld.levels) if kind == "multinomial" else 1
keep_eff = ld.fe is not None and ld.n_groups * m * n_lambdas <= 5_000_000
chosen = _choose_solver(solver, model, folds, options)
info["solver"] = chosen
path = _categorical.fit_path(model, l1_ratio=l1_ratio, penalty=penalty
if not isinstance(penalty, str) else None,
n_lambdas=n_lambdas,
lambda_min_ratio=lambda_min_ratio,
standardize=standardize, tol=tol, cv=needs_cv,
keep_effects_path=keep_eff, grouped=grouped,
solver=chosen)
index, rule = _fit.choose(path, penalty)
effects = path.effects
if ld.fe is not None:
if path.effects_path is not None:
effects = path.effects_path[index]
elif index != len(path.lambdas) - 1:
# the effects kept are the last penalty's; refit at the chosen one
again = _categorical.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,
grouped=grouped, solver=chosen)
effects = again.effects
info["effects_refit_passes"] = again.timings["passes"]
if kind == "ordered":
effects = np.ravel(effects)
finally:
ld = model.ld
ld.cleanup()
names, coef, unpen, intercept, cutnames, cuts, scale = _report(model, path)
diag = {**ld.diagnostics, **path.timings, **info, "scale": scale,
"separation": ld.separation}
return PenalizedCategoricalResult(
formula=fml, depvar=model.depvar, coefnames=names, unpenalized=unpen,
fe_names=list(model.fe), l1_ratio=float(l1_ratio), lambdas=path.lambdas,
coef_path=coef, intercept_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,
model=kind, link=link, grouped=bool(grouped), levels=list(ld.levels),
covariates=list(model.names),
cutnames=cutnames, cutpoints_path=cuts, effects=effects, fe_levels=ld.fe_levels,
deviance=path.deviance, cv_folds=path.cv_folds, _source=data)
_DOC = """
Minimizes ``-(1/W) sum_i w_i loglik_i + penalty * {form}`` over
standardized covariates, W the sum of the weights: {objective}. The
{location} not penalized. Each step of the fit is one read of the data
(stored once, by logit-stream), shared by the cross-validation's models;
a path takes a few reads per penalty. Needs logit-stream (``pip install
'penalized-stream[logit]'``).
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), or a value.
levels : list, optional
The outcome's levels, in order ({levels}); default its sorted values
(an Enum's own order).
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 effects would be infinite in a fold's training rows
({fold_infinite}) 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 penalized coefficients, 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 (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 (Friedman, Hastie and
Tibshirani 2010): the
faster choice when the rows fit. ``"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 of the
full-sample and cross-validation models fit within ``max_memory_gb``
(else the machine's available memory) and each model's per-row
state, 16 bytes per row and outcome level, fits in both the CPU's
last-level cache and 6 MB (about 100,000 rows of a four-level
outcome); otherwise it streams. Past that, coordinate descent waits
on memory for the rows it reads, and the streamed solver is faster.
Where the solvers cross over depends on the machine: about 150,000
rows of a four-level outcome on an 8-core laptop with a 12 MB cache,
and about 50,000 on a 16-vCPU server. Near the crossover, setting the
solver can be faster than ``"auto"``. The ordered models use the
streamed solver.
**options
Options for the stored rows: ``workdir``, ``storage``, ``dtype``,
``block_mb``, ``chunk_mb``, ``max_memory_gb``, ``verbose``; and
``n_threads``.
Returns
-------
PenalizedCategoricalResult
"""
_KIND_DOC = {
("multinomial", "logit"): dict(
name="multinomial logit", fn="mlogit",
objective="glmnet's multinomial objective, with its ungrouped penalty (each level's "
"coefficient on its own); every covariate has a coefficient for each "
"outcome level, identified by the penalty (glmnet's symmetric form)",
location="intercepts, or with one absorbed fixed effect each group's effects, are",
outcome="an outcome with two or more unordered levels",
infinite="an outcome that never varies",
fold_infinite="an outcome that never varies, or a level its held-out rows have and "
"its training rows do not",
levels="their order only names the coefficients"),
("ordered", "logit"): dict(
name="ordered logit", fn="ologit",
objective="ordinalNet's for its parallel cumulative logit, with P(y <= j) = "
"F(cut_j - x'b) (ordinalNet's slopes have the opposite sign)",
location="cutpoints, and with one absorbed fixed effect each group's location, are",
outcome="an ordered outcome with two or more levels",
infinite="every row at the lowest level, or every row at the highest",
fold_infinite="every training row at the lowest level, or every one at the highest",
levels="lowest first"),
("ordered", "probit"): dict(
name="ordered probit", fn="oprobit",
objective="ordinalNet's for its parallel cumulative probit, with P(y <= j) = "
"Phi(cut_j - x'b) (ordinalNet's slopes have the opposite sign)",
location="cutpoints, and with one absorbed fixed effect each group's location, are",
outcome="an ordered outcome with two or more levels",
infinite="every row at the lowest level, or every row at the highest",
fold_infinite="every training row at the lowest level, or every one at the highest",
levels="lowest first"),
}
def _doc(d, form):
return _DOC.format(form=form, objective=d["objective"], location=d["location"],
outcome=d["outcome"], infinite=d["infinite"],
fold_infinite=d["fold_infinite"], levels=d["levels"])
_GROUPED = """ grouped : bool, default False
glmnet's ``type.multinomial = "grouped"``: penalize each covariate's
coefficients for all the levels by their norm, so that the covariate
enters or leaves every level's equation together (its coefficients
are then unique, and sum to zero over the levels). The default
penalizes each coefficient on its own (glmnet's ``"ungrouped"``).
"""
def _lasso(kind, link):
def fit(fml: str, data: Any, *, penalty: str | float = "cv", levels=None,
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) -> PenalizedCategoricalResult:
return _run(fml, data, kind=kind, link=link, levels=levels, 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, options=options, solver=solver)
def fit_mlogit(fml: str, data: Any, *, penalty: str | float = "cv", grouped: bool = False,
levels=None, 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) -> PenalizedCategoricalResult:
return _run(fml, data, kind=kind, link=link, levels=levels, 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, options=options, grouped=grouped,
solver=solver)
d = _KIND_DOC[(kind, link)]
if kind == "multinomial":
fit = fit_mlogit
fit.__name__ = fit.__qualname__ = f"lasso_{d['fn']}_stream"
fit.__doc__ = (f"The lasso {d['name']}: an L1 penalty on the covariates.\n"
+ _doc(d, "sum |b|") + (_GROUPED if kind == "multinomial" else ""))
return fit
def _elastic_net(kind, link):
def fit(fml: str, data: Any, *, l1_ratio: float = 0.5, penalty: str | float = "cv",
levels=None, 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) -> PenalizedCategoricalResult:
return _run(fml, data, kind=kind, link=link, levels=levels, 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, options=options, solver=solver)
def fit_mlogit(fml: str, data: Any, *, l1_ratio: float = 0.5,
penalty: str | float = "cv", grouped: bool = False, levels=None,
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) -> PenalizedCategoricalResult:
return _run(fml, data, kind=kind, link=link, levels=levels, 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, options=options, grouped=grouped,
solver=solver)
d = _KIND_DOC[(kind, link)]
if kind == "multinomial":
fit = fit_mlogit
fit.__name__ = fit.__qualname__ = f"elastic_net_{d['fn']}_stream"
fit.__doc__ = (f"The elastic-net {d['name']}: a mix of L1 and L2 penalties.\n"
+ _doc(d, "sum (l1_ratio |b| + (1 - l1_ratio)/2 b^2)")
+ """ l1_ratio : float, default 0.5
The L1 share of the penalty (glmnet's alpha): 1 is the lasso.
""" + (_GROUPED if kind == "multinomial" else ""))
return fit
lasso_mlogit_stream = _lasso("multinomial", "logit")
elastic_net_mlogit_stream = _elastic_net("multinomial", "logit")
lasso_ologit_stream = _lasso("ordered", "logit")
elastic_net_ologit_stream = _elastic_net("ordered", "logit")
lasso_oprobit_stream = _lasso("ordered", "probit")
elastic_net_oprobit_stream = _elastic_net("ordered", "probit")