"""The result of a lasso, ridge or elastic-net fit."""
from __future__ import annotations
import json
import logging
from dataclasses import dataclass, field
from pathlib import Path as FilePath
from typing import Any
import numpy as np
import polars as pl
from hdfe_stream.core.utils import as_lazy
from ._folds import FOLD
_METHODS = {1.0: "Lasso", 0.0: "Ridge"}
[docs]
@dataclass
class PenalizedResult:
"""A penalized least-squares fit along a path of penalties, and the
penalty chosen on it.
Coefficients are on the covariates' own scale (the standardization is
undone). There are no standard errors: after selection by a penalty they
would not be valid. For inference on a coefficient of interest, use
`double_selection_stream`.
Attributes
----------
formula : str
depvar : str
coefnames : list of str
The covariates, in design order, penalized and unpenalized.
unpenalized : list of str
fe_names : list of str
The fixed effects partialled out (not penalized).
l1_ratio : float
1 for the lasso, 0 for ridge, in between for the elastic net.
lambdas : numpy.ndarray
The penalties of the path, from the largest.
coef_path : numpy.ndarray, shape (n_lambdas, n_coef)
intercept_path : numpy.ndarray
Zero with fixed effects (they absorb it).
penalty : float
The chosen penalty.
penalty_rule : str
How it was chosen: ``"lambda_min"`` or ``"lambda_1se"`` (cross-validation),
``"aic"``, ``"bic"``, ``"ebic"``, ``"aicc"``, ``"rigorous"`` or ``"given"``.
index : int
The chosen penalty's position on the path.
cv_mean, cv_se : numpy.ndarray or None
The cross-validated mean squared error at each penalty, and its
standard error (None without cross-validation).
n_folds : int or None
fold_by : str or None
``"rows"``, or the column whose values make the folds.
criteria : dict
``{"aic": array, "bic": ..., "ebic": ..., "aicc": ...}`` along the path.
df : numpy.ndarray
Degrees of freedom of the penalized fit along the path.
n_obs : int
k_fe : int
The fixed effects' degrees of freedom.
n_levels : dict
dropped : list of str
Covariates with no variation left after the fixed effects.
groups : dict or None
With ``groups=``: each covariate's group (``{name: group}``).
diagnostics : dict
"""
formula: str
depvar: str
coefnames: list[str]
unpenalized: list[str]
fe_names: list[str]
l1_ratio: float
lambdas: np.ndarray
coef_path: np.ndarray
intercept_path: np.ndarray
penalty: float
penalty_rule: str
index: int
cv_mean: np.ndarray | None
cv_se: np.ndarray | None
n_folds: int | None
fold_by: str | None
criteria: dict
df: np.ndarray
n_obs: int
k_fe: int
n_levels: dict
dropped: list[str]
weights: Any = None
weights_type: str = "aweights"
cv_fixed_effects: str | None = None
loadings: np.ndarray | None = None
groups: dict | None = None
diagnostics: dict = field(default_factory=dict)
_exprs: dict = field(default_factory=dict, repr=False)
_cp: Any = field(default=None, repr=False)
#: what the cross-validated error measures
cv_measure = "mean squared error"
# ------------------------------------------------------------ choices
@property
def method(self) -> str:
return _METHODS.get(self.l1_ratio, "Elastic net")
def _index(self, which):
if which is None or which == "selected":
return self.index
if which in ("lambda_min", "lambda_1se"):
if self.cv_mean is None:
raise ValueError(f"{which} needs cross-validation (n_folds)")
i = int(np.argmin(self.cv_mean))
if which == "lambda_min":
return i
ok = self.cv_mean <= self.cv_mean[i] + self.cv_se[i]
return int(np.argmax(ok))
if which in self.criteria:
return int(np.argmin(self.criteria[which]))
if isinstance(which, (int, np.integer)) and not isinstance(which, bool):
return int(which)
raise ValueError(f"which must be 'selected', 'lambda_min', 'lambda_1se', a "
f"criterion ({sorted(self.criteria)}) or a path index; got {which!r}")
@property
def lambda_min(self) -> float | None:
return None if self.cv_mean is None else float(self.lambdas[self._index("lambda_min")])
@property
def lambda_1se(self) -> float | None:
return None if self.cv_mean is None else float(self.lambdas[self._index("lambda_1se")])
# ------------------------------------------------------- coefficients
[docs]
def coef(self, which=None) -> dict:
"""``{name: coefficient}`` at the chosen penalty (or at `which`:
``"lambda_min"``, ``"lambda_1se"``, a criterion name, or a path index),
with ``"Intercept"`` first when there are no fixed effects."""
i = self._index(which)
out = {} if self.fe_names else {"Intercept": float(self.intercept_path[i])}
out.update({nm: float(b) for nm, b in zip(self.coefnames, self.coef_path[i], strict=True)})
return out
[docs]
def selected(self, which=None) -> list[str]:
"""The covariates with a nonzero coefficient (unpenalized ones included)."""
i = self._index(which)
return [nm for nm, b in zip(self.coefnames, self.coef_path[i], strict=True) if b != 0.0]
[docs]
def tidy(self, which=None) -> pl.DataFrame:
"""One row per covariate: ``term``, ``estimate``, ``penalized``."""
i = self._index(which)
terms = ([] if self.fe_names else ["Intercept"]) + list(self.coefnames)
est = ([] if self.fe_names else [float(self.intercept_path[i])]) + \
[float(b) for b in self.coef_path[i]]
pen = ([] if self.fe_names else [False]) + \
[nm not in self.unpenalized for nm in self.coefnames]
out = pl.DataFrame({"term": terms, "estimate": est, "penalized": pen})
if self.groups is not None:
out = out.with_columns(pl.Series("group", [
self.groups.get(t, t) for t in terms]))
return out
[docs]
def path(self) -> pl.DataFrame:
"""The whole path, long: ``lambda``, ``term``, ``estimate``."""
L, k = self.coef_path.shape
return pl.DataFrame({
"lambda": np.repeat(self.lambdas, k),
"term": np.tile(np.array(self.coefnames, dtype=object), L).tolist(),
"estimate": self.coef_path.ravel(),
})
[docs]
def cv(self) -> pl.DataFrame:
"""The penalty path's summary: ``lambda``, ``n_nonzero``, ``df``, the
cross-validated error (``cv_mean``, ``cv_se``) and the criteria."""
cols = {"lambda": self.lambdas,
"n_nonzero": (self.coef_path != 0).sum(axis=1).astype(np.int64),
"df": self.df}
if self.cv_mean is not None:
cols.update(cv_mean=self.cv_mean, cv_se=self.cv_se)
cols.update({k: v for k, v in self.criteria.items()})
return pl.DataFrame(cols)
# ---------------------------------------------------------- prediction
[docs]
def predict(self, newdata=None, which=None) -> pl.LazyFrame:
"""`newdata` (by default the data fitted), lazily, with ``xb`` added:
the covariates' part of the prediction, plus the intercept when there
are no fixed effects. With fixed effects, ``xb`` leaves out their
effects, which the fit partials out without estimating."""
if newdata is None:
if self._cp is None:
raise ValueError("this result holds no reference to its data")
newdata = self._cp._sample["source"]
frame = as_lazy(newdata)
if FOLD in frame.collect_schema():
frame = frame.drop(FOLD)
i = self._index(which)
terms = [float(b) * self._exprs[nm]
for nm, b in zip(self.coefnames, self.coef_path[i], strict=True) if b != 0.0]
base = pl.lit(0.0 if self.fe_names else float(self.intercept_path[i]))
value = pl.sum_horizontal([base, *terms]) if terms else base
return frame.with_columns(value.cast(pl.Float64).alias("xb"))
[docs]
def sample(self, check: bool = True) -> pl.LazyFrame:
"""The source with ``row_id``, ``in_sample`` and ``dropped_because``
added, as `hdfe_stream`'s results give them."""
frame = self._cp.sample(check)
return frame.drop(FOLD) if FOLD in frame.collect_schema() else frame
# ------------------------------------------------------------- report
def summary_dict(self, coefficients: bool = True) -> dict:
out = {"method": self.method, "formula": self.formula, "depvar": self.depvar,
"n_obs": self.n_obs, "fixed_effects": list(self.fe_names),
"n_levels": dict(self.n_levels), "l1_ratio": self.l1_ratio,
"penalty": self.penalty, "penalty_rule": self.penalty_rule,
"lambda_min": self.lambda_min, "lambda_1se": self.lambda_1se,
"n_folds": self.n_folds, "fold_by": self.fold_by,
"cv_fixed_effects": self.cv_fixed_effects,
"n_covariates": len(self.coefnames), "n_selected": len(self.selected()),
"unpenalized": list(self.unpenalized), "dropped": list(self.dropped)}
if self.cv_mean is not None:
out["cv_mean"] = float(self.cv_mean[self.index])
out["cv_se"] = float(self.cv_se[self.index])
if coefficients:
out["coefficients"] = {k: v for k, v in self.coef().items() if v != 0.0}
return out
def summary_json(self, path: str | FilePath | None = None, indent: int | None = 2):
text = json.dumps(self.summary_dict(), indent=indent, default=float)
if path is not None:
FilePath(path).write_text(text)
return text
def summary_text(self) -> str:
i = self.index
lines = [f"### {self.formula}"]
head = f"{self.method}"
if self.method.startswith("Elastic net"):
head += f" (l1_ratio {self.l1_ratio:g})"
rule = {"lambda_min": "cross-validation, lambda_min",
"lambda_1se": "cross-validation, lambda_1se",
"given": "given"}.get(self.penalty_rule, self.penalty_rule)
lines.append(f"{head} penalty: {self.penalty:.6g} ({rule})")
obs = f"obs: {self.n_obs:,}"
for d in self.fe_names:
obs += f" {d}: {self.n_levels.get(d, 0):,}"
lines.append(obs)
sel = self.selected()
line = (f"selected: {len(sel)} of {len(self.coefnames)} covariates"
+ (f" ({len(self.unpenalized)} unpenalized)" if self.unpenalized else ""))
if self.groups is not None:
groups = list(dict.fromkeys(self.groups.values()))
chosen = list(dict.fromkeys(self.groups[n] for n in sel))
line += f"; {len(chosen)} of {len(groups)} groups"
lines.append(line)
if self.cv_mean is not None:
cv = (f"CV ({self.n_folds} folds by {self.fold_by}): {self.cv_measure} "
f"{self.cv_mean[i]:.6g} (se {self.cv_se[i]:.3g})")
cv += f" lambda_min: {self.lambda_min:.6g} lambda_1se: {self.lambda_1se:.6g}"
lines.append(cv)
if self.dropped:
lines.append(f"dropped (no variation left): {', '.join(self.dropped)}")
table = self.tidy().filter(pl.col("estimate") != 0.0)
with pl.Config(tbl_rows=-1, tbl_hide_dataframe_shape=True):
lines.append(str(table))
return "\n".join(lines)
def summary(self, logger: logging.Logger | None = None) -> None:
text = self.summary_text()
if logger is not None:
logger.info(text)
else:
print(text)
def __repr__(self) -> str:
return (f"PenalizedResult({self.method}, {self.formula!r}, penalty={self.penalty:.4g}"
f" ({self.penalty_rule}), {len(self.selected())} of {len(self.coefnames)} "
"selected)")
# --------------------------------------------------------------- plots
[docs]
def plot_path(self, ax=None, log=True):
"""The coefficients of the standardized covariates along the path,
with the chosen penalty marked."""
from hdfe_stream.core.plots import require_matplotlib
plt = require_matplotlib("plotting")
if ax is None:
_, ax = plt.subplots(figsize=(7, 4))
scale = self.diagnostics.get("scale")
B = self.coef_path * (scale if scale is not None else 1.0)
x = np.log(self.lambdas) if log else self.lambdas
ax.plot(x, B, linewidth=1)
ax.axvline(x[self.index], color="0.4", linestyle="--", linewidth=1)
ax.set_xlabel("log(penalty)" if log else "penalty")
ax.set_ylabel("coefficient (standardized covariate)")
ax.invert_xaxis()
return ax
[docs]
def plot_cv(self, ax=None, log=True):
"""The cross-validated error along the path, with one
standard error either side, and lambda_min and lambda_1se marked."""
if self.cv_mean is None:
raise ValueError("there is no cross-validation to plot (n_folds=None)")
from hdfe_stream.core.plots import require_matplotlib
plt = require_matplotlib("plotting")
if ax is None:
_, ax = plt.subplots(figsize=(7, 4))
x = np.log(self.lambdas) if log else self.lambdas
ax.errorbar(x, self.cv_mean, yerr=self.cv_se, fmt="o", markersize=3,
elinewidth=0.8, capsize=0)
for w in ("lambda_min", "lambda_1se"):
ax.axvline(x[self._index(w)], color="0.4", linestyle="--", linewidth=1)
ax.set_xlabel("log(penalty)" if log else "penalty")
ax.set_ylabel(f"cross-validated {self.cv_measure}")
ax.invert_xaxis()
return ax