"""Stability selection (Meinshausen and Buhlmann 2010) with complementary
pairs (Shah and Samworth 2013), as R's stabs computes it with glmnet's lasso.
One pass splits the rows into shards (by row, or by a column's groups). Each
of `n_pairs` pairs takes a random half of the shards and the other half; on
each half, the lasso path is fitted from the cross-products (no further
pass), and the covariates selected are those nonzero at the last penalty
before more than q have ever been active (stabs' ``glmnet.lasso``, glmnet's
``pmax = q``). A covariate's selection probability is the share of the
2 x n_pairs halves that select it; the stable set is those at or above
`cutoff`. The expected number of false selections is bounded by `pfer`:
q^2 / ((2 cutoff - 1) p) with no assumption, or Shah and Samworth's tighter
bound under unimodality (stabs' default).
"""
from __future__ import annotations
import math
import warnings
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from typing import Any
import numpy as np
import polars as pl
from hdfe_stream.core.utils import single_blas
from scipy.optimize import brentq
from . import _design, _fit, _groups
from ._solver import fit_path, group_basis, group_fit_path, unpenalized_start
from ._subset import sub_design
ASSUMPTIONS = ("unimodal", "none")
def _um_const(cutoff, B, theta):
"""Shah and Samworth's constant under unimodality (stabs' um_const)."""
if cutoff <= 0.75:
if cutoff < 0.5 + min(theta ** 2, 1 / (2 * B) + 0.75 * theta ** 2):
raise ValueError("cutoff out of bounds for the unimodal bound")
return 2 * (2 * cutoff - 1 - 1 / (2 * B))
if cutoff > 1:
raise ValueError("cutoff out of bounds")
return (1 + 1 / B) / (4 * (1 - cutoff + 1 / (2 * B)))
def parameters(p, cutoff, q, pfer, n_pairs, assumption):
"""(q, pfer bound) from the cutoff and one of q or pfer (stabs'
stabsel_parameters)."""
if not 0.5 < cutoff <= 1:
raise ValueError("cutoff must be above 0.5 and at most 1")
if (q is None) == (pfer is None):
raise ValueError("give the cutoff and one of q or pfer")
if assumption not in ASSUMPTIONS:
raise ValueError(f"assumption must be one of {ASSUMPTIONS}")
B = n_pairs
def bound(qq):
if assumption == "none":
return qq ** 2 / p / (2 * cutoff - 1)
return qq ** 2 / p / _um_const(cutoff, B, qq / p)
if q is None:
if assumption == "none":
q = math.floor(math.sqrt(pfer * (2 * cutoff - 1) * p))
else:
if cutoff <= 0.75:
upper = max(p * math.sqrt(cutoff - 0.5),
p * math.sqrt(4 / 3 * (cutoff - 0.5 - 1 / (2 * B))))
upper = math.ceil(upper - 1)
else:
upper = p
q = math.floor(brentq(lambda qq: bound(qq) - pfer, 1, upper))
q = max(1, q)
if not 0 < q <= p:
raise ValueError(f"q must be between 1 and the number of candidates ({p})")
return int(q), float(bound(q))
[docs]
@dataclass
class StabilityResult:
"""Stability selection: each candidate's selection probability, and the
stable set.
Attributes
----------
formula : str
candidates : list of str
The penalized covariates, or with `groups` the groups.
probabilities : dict
``{candidate: share of the subsamples that select it}``.
selected : list of str
The stable set: probability at or above `cutoff`.
cutoff : float
q : int
Candidates selected on each subsample (at most).
pfer : float
The bound on the expected number of false selections.
assumption : str
n_subsamples : int
path : numpy.ndarray
(steps, candidates): the share selected at each step of the path
(stabs' ``phat``, transposed).
groups : dict or None
Each covariate's group, with `groups=`.
subsamples : list of list of int
Each subsample's shards (pairs: entries 2i and 2i + 1).
"""
formula: str
candidates: list
probabilities: dict
selected: list
cutoff: float
q: int
pfer: float
assumption: str
n_subsamples: int
path: Any = None
groups: dict | None = None
unpenalized: list = field(default_factory=list)
n_obs: int = 0
fe_names: list = field(default_factory=list)
subsamples: list = field(default_factory=list)
def tidy(self) -> pl.DataFrame:
cands = list(self.candidates)
return pl.DataFrame({
"candidate": cands,
"probability": [self.probabilities[c] for c in cands],
"selected": [c in self.selected for c in cands],
}).sort("probability", descending=True, maintain_order=True)
[docs]
def selected_covariates(self) -> list[str]:
"""The covariates in the stable set (with groups, every member of a
stable group), unpenalized ones included."""
if self.groups is None:
return list(self.selected) + list(self.unpenalized)
return [nm for nm, g in self.groups.items()
if g in self.selected or nm in self.unpenalized]
def summary_text(self) -> str:
lines = [f"### {self.formula}",
f"stability selection: {len(self.selected)} of {len(self.candidates)} "
f"stable at cutoff {self.cutoff:g}; q = {self.q} per subsample, "
f"{self.n_subsamples} subsamples; expected false selections at most "
f"{self.pfer:.3g} ({self.assumption})",
f"obs: {self.n_obs:,}" + (f" fixed effects: {' + '.join(self.fe_names)}"
if self.fe_names else "")]
with pl.Config(tbl_rows=-1, tbl_hide_dataframe_shape=True):
lines.append(str(self.tidy().filter(pl.col("probability") > 0)))
return "\n".join(lines)
def summary(self) -> None:
print(self.summary_text())
[docs]
def plot_path(self, ax=None):
"""The selection probabilities along the path, with the cutoff."""
from hdfe_stream.core.plots import require_matplotlib
plt = require_matplotlib("plotting")
if ax is None:
_, ax = plt.subplots(figsize=(7, 4))
ax.plot(np.arange(1, self.path.shape[0] + 1), self.path, linewidth=1)
ax.axhline(self.cutoff, color="0.4", linestyle="--", linewidth=1)
ax.set_xlabel("step of the path")
ax.set_ylabel("selection probability")
return ax
def _selection(path_coef, ids, q):
"""stabs' glmnet.lasso with pmax = q: the support at the last step at
which at most q candidates have ever been active, and the path up to it."""
G = int(ids.max()) + 1
support = np.zeros((path_coef.shape[0], G), dtype=bool)
for g in range(G):
support[:, g] = (path_coef[:, ids == g] != 0).any(axis=1)
ever = np.logical_or.accumulate(support, axis=0).sum(axis=1)
last = int(np.flatnonzero(ever <= q).max()) if (ever <= q).any() else 0
return support[last], support[:last + 1]
[docs]
def stability_selection_stream(fml: str, data: Any, *, cutoff: float = 0.75,
pfer: float | None = 1.0, q: int | None = None,
assumption: str = "unimodal", n_pairs: int = 50,
n_shards: int = 20, l1_ratio: float = 1.0, groups=None,
unpenalized=None, weights=None, weights_type: str = "aweights",
fold_by: str | None = None, seed: int = 0,
standardize: bool = True, n_lambdas: int = 100,
lambda_min_ratio: float | None = None, tol: float = 1e-7,
n_threads: int | None = None, **options) -> StabilityResult:
"""Stability selection with complementary pairs, as stabs computes it.
Parameters
----------
fml : str
A pyfixest formula, as for `lasso_stream`.
data : str, Path, polars.LazyFrame or polars.DataFrame
cutoff : float, default 0.75
A candidate is stable when at least this share of the subsamples select it.
pfer : float, default 1
The bound on the expected number of false selections; with `cutoff`,
it sets q. Give `q` instead (and ``pfer=None``) to fix q.
q : int, optional
The candidates selected on each subsample (at most).
assumption : {"unimodal", "none"}, default "unimodal"
Shah and Samworth's bound under unimodality (stabs' default), or the
bound that needs no assumption, q^2 / ((2 cutoff - 1) p).
n_pairs : int, default 50
Complementary pairs of half-samples (100 subsamples).
n_shards : int, default 20
The pieces the rows are split into in the pass (an even number); each
half-sample is half of them. By row, or by `fold_by`'s groups.
l1_ratio, groups, unpenalized, weights, weights_type, fold_by
As for `lasso_stream`. Unpenalized covariates are always kept and are
not candidates; with `groups`, the candidates are the groups.
seed, standardize, n_lambdas, lambda_min_ratio, tol
As for `lasso_stream`.
n_threads : int, optional
Threads for the subsamples' fits.
**options
hdfe-stream's options.
Returns
-------
StabilityResult
"""
if n_shards < 2 or n_shards % 2:
raise ValueError("n_shards must be an even number of at least 2")
if not isinstance(n_pairs, int) or n_pairs < 1:
raise ValueError("n_pairs must be a positive integer")
design = _design.build(fml, data, unpenalized=unpenalized, weights=weights,
weights_type=weights_type, n_folds=n_shards, fold_by=fold_by,
seed=seed, options=options)
names, unpen = design.names, design.unpenalized
labels, ids = _groups.assign(names, groups, unpen)
pen = [i for i, nm in enumerate(names) if nm not in unpen]
cand_labels = list(dict.fromkeys(labels[i] for i in pen))
cand_ids = np.array([cand_labels.index(labels[i]) if i in pen else -1
for i in range(len(names))])
p = len(cand_labels)
q, bound = parameters(p, cutoff, q, pfer, n_pairs, assumption)
rng = np.random.default_rng(seed)
halves = []
for _ in range(n_pairs):
perm = rng.permutation(n_shards)
halves += [sorted(perm[: n_shards // 2]), sorted(perm[n_shards // 2:])]
gids = ids if groups is not None else None
pf = _fit.penalty_factors(names, unpen)
full = _fit.full_moments(design.cp, standardize)
dropped = [nm for nm, ok in zip(names, full.usable, strict=True) if not ok]
if dropped:
warnings.warn(f"{len(dropped)} covariates have no variation left after the fixed "
f"effects and are dropped: {dropped}", stacklevel=2)
def one(splits):
# the path alone: no degrees of freedom or criteria, which the
# selection does not use, and each group's basis formed once
sub = sub_design(design, design.depvar, names, unpen, splits=splits)
m = _fit.full_moments(sub.cp, standardize)
b0 = unpenalized_start(m, pf)
gb = group_basis(m, gids, pf) if gids is not None else None
lambdas = _fit.path_lambdas(m, pf, l1_ratio, b0, gids, n_lambdas, lambda_min_ratio,
gb)
if gb is not None:
coef, _, _ = group_fit_path(m, lambdas, l1_ratio, pf, gids, tol, gb=gb)
else:
coef, _, _ = fit_path(m, lambdas, l1_ratio, pf, tol)
return _selection(coef[:, pen], cand_ids[pen], q)
# the subsamples run in parallel, so BLAS gets one thread
with single_blas(), ThreadPoolExecutor(max_workers=n_threads or 8) as ex:
results = list(ex.map(one, halves))
sel = np.array([s for s, _ in results], dtype=float)
probs = sel.mean(axis=0)
steps = max(len(pth) for _, pth in results)
padded = [np.vstack([pth, np.repeat(pth[-1:], steps - len(pth), axis=0)])
for _, pth in results]
path_prob = np.mean(padded, axis=0)
probabilities = dict(zip(cand_labels, map(float, probs), strict=True))
return StabilityResult(
formula=fml, candidates=cand_labels, probabilities=probabilities,
selected=[c for c in cand_labels if probabilities[c] >= cutoff], cutoff=cutoff,
q=q, pfer=bound, assumption=assumption, n_subsamples=len(halves), path=path_prob,
groups=dict(zip(names, labels, strict=True)) if groups is not None else None,
unpenalized=list(unpen), n_obs=design.cp.n_obs, fe_names=list(design.fe),
subsamples=[list(map(int, h)) for h in halves])