from __future__ import annotations
import os
import platform
import warnings
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
import numpy as np
try: # optional: sklearn L-BFGS as initializer for the logistic solver
from sklearn.linear_model import LogisticRegression
_HAS_SK = True
except Exception: # pragma: no cover
_HAS_SK = False
try: # optional: scipy for chi2 quantiles
from scipy.linalg import solve_triangular
from scipy.stats import chi2
_HAS_SCIPY = True
except Exception: # pragma: no cover
_HAS_SCIPY = False
Array = np.ndarray
def _sigmoid(z: Any) -> Array:
"""Numerically stable sigmoid; never overflows (exp is only applied to -|z|)."""
z = np.asarray(z, dtype=float)
e = np.exp(-np.abs(z))
return np.where(z >= 0, 1.0 / (1.0 + e), e / (1.0 + e))
def _quartic_level_root(T: Array, Q: Array, eps: float, r: float) -> Array:
"""Smallest ``tau > 0`` with ``tau²/2 + tau³T/6 + tau⁴Q/24 = eps``, elementwise, by bisection.
``r = sqrt(2 eps)`` is the root when ``T = Q = 0`` and seeds the bracket. ``inf`` where the
quartic stays below ``eps`` (no boundary on that side).
"""
def f(tau: Array) -> Array:
return tau * tau / 2.0 + tau**3 * T / 6.0 + tau**4 * Q / 24.0 - eps
lo = np.zeros(len(T))
hi = np.full(len(T), r)
for _ in range(12): # grow the bracket while the quartic is still below eps
below = f(hi) < 0
if not np.any(below):
break
hi[below] *= 1.5
no_root = f(hi) < 0
for _ in range(60):
mid = 0.5 * (lo + hi)
neg = f(mid) < 0
lo = np.where(neg, mid, lo)
hi = np.where(neg, hi, mid)
return np.where(no_root, np.inf, 0.5 * (lo + hi))
def _logistic_ray_root(
z: Array, Z: Array, y: Array, sw: Array, pen_lin: Array, pen_quad: Array, eps: float, r: float
) -> Array:
"""For each column ``k`` of ``Z``, the ``tau > 0`` at which the loss gap along the ray
``theta_hat + tau * u_k`` equals ``eps``; ``Z[:, k] = X @ u_k`` and ``z = X @ theta_hat``.
The gap is ``mean(sw * (psi(z + tau Z) - psi(z) - y tau Z)) + pen_lin tau + pen_quad tau²``
with ``psi(t) = log(1 + e^t)``; it is convex in ``tau`` and 0 at ``tau = 0``, so the root is
unique. ``inf`` where the gap never reaches ``eps`` (a direction of recession).
"""
base = np.mean(sw[:, None] * np.logaddexp(0.0, z)[:, None], axis=0)
score = np.mean((sw * y)[:, None] * Z, axis=0)
def gap(tau: Array) -> Array:
data = np.mean(sw[:, None] * np.logaddexp(0.0, z[:, None] + tau[None, :] * Z), axis=0) - base
return data - tau * score + pen_lin * tau + pen_quad * tau * tau - eps
k = Z.shape[1]
lo = np.zeros(k)
hi = np.full(k, r)
for _ in range(40):
below = gap(hi) < 0
if not np.any(below):
break
hi[below] *= 2.0
no_root = gap(hi) < 0
for _ in range(50):
mid = 0.5 * (lo + hi)
neg = gap(mid) < 0
lo = np.where(neg, mid, lo)
hi = np.where(neg, hi, mid)
return np.where(no_root, np.inf, 0.5 * (lo + hi))
def _ess_geyer(chain: Array) -> float:
"""Effective sample size of a scalar chain (Geyer 1992, initial positive sequence).
The integrated autocorrelation time is ``tau = -1 + 2 * sum_m G_m`` where
``G_m = rho_{2m} + rho_{2m+1}`` are sums of consecutive autocorrelation pairs; the
sum stops at the first non-positive ``G_m`` and the sequence is forced to be
non-increasing (initial monotone sequence). ``ESS = n / tau``, capped at ``n``.
For an AR(1) chain this reduces to ``n (1 - rho) / (1 + rho)``.
"""
x = np.asarray(chain, dtype=float)
n = x.shape[0]
x = x - x.mean()
var = float(x @ x) / n
if n < 4 or var <= 1e-300:
return float(n)
f = np.fft.rfft(x, 2 * n)
acov = np.fft.irfft(f * np.conj(f))[:n] / n
rho = acov / acov[0]
tau = -1.0
prev = np.inf
for m in range(n // 2):
g = rho[2 * m] + rho[2 * m + 1]
if g <= 0.0:
break
g = min(g, prev)
prev = g
tau += 2.0 * g
tau = max(tau, 1.0 / n)
return float(min(n, max(1.0, n / tau)))
class _MembershipOracle:
"""Vectorized penalized objective and membership checks.
Parameters are shared with the fitted :class:`RashomonSet` instance and the
oracle exposes helpers that optionally accept pre-computed ``X @ theta``
values to avoid repeated matrix multiplications (critical for Hit-and-Run
style sampling in D14).
"""
__slots__ = (
"_estimator",
"_X",
"_y",
"_lam",
"_reg_mask",
"_sw",
"_L_hat",
"_epsilon",
"_tol",
"_n",
"_d",
)
def __init__(
self,
*,
estimator: str,
X: Array,
y: Array,
lam: float,
L_hat: float,
epsilon: float,
tol: float,
reg_mask: Optional[Array] = None,
sample_weight: Optional[Array] = None,
) -> None:
self._estimator = estimator
self._X = X
self._y = y
self._lam = float(lam)
self._L_hat = float(L_hat)
self._epsilon = float(epsilon)
self._tol = float(tol)
self._n = X.shape[0]
self._d = X.shape[1]
# reg_mask[j] = 1 if coordinate j is penalized, 0 otherwise (e.g. intercept).
self._reg_mask = np.ones(self._d, dtype=float) if reg_mask is None else np.asarray(reg_mask, dtype=float)
# per-row weights with mean 1, so the data term is mean(sw * loss)
self._sw = np.ones(self._n, dtype=float) if sample_weight is None else np.asarray(sample_weight, dtype=float)
# ------------------------------------------------------------------ utils
def with_tolerance(self, tol: float) -> _MembershipOracle:
"""Return a cloned oracle with a different membership tolerance."""
return _MembershipOracle(
estimator=self._estimator,
X=self._X,
y=self._y,
lam=self._lam,
L_hat=self._L_hat,
epsilon=self._epsilon,
tol=tol,
reg_mask=self._reg_mask,
sample_weight=self._sw,
)
def _validate_theta(self, theta: Array) -> Array:
arr = np.asarray(theta, dtype=float)
if arr.ndim != 1 or arr.shape[0] != self._d:
raise ValueError("theta must be a 1D vector of length d")
return arr
def _validate_thetas(self, Theta: Array) -> Array:
arr = np.asarray(Theta, dtype=float)
if arr.ndim == 1:
arr = arr[None, :]
if arr.ndim != 2 or arr.shape[1] != self._d:
raise ValueError("Theta must have shape (k, d)")
return arr
def _resolve_scores_single(self, theta: Array, x_theta: Optional[Array]) -> Array:
if x_theta is None:
return (self._X @ theta).astype(float, copy=False)
scores = np.asarray(x_theta, dtype=float)
if scores.ndim == 2:
scores = scores.reshape(-1)
if scores.ndim != 1 or scores.shape[0] != self._n:
raise ValueError("x_theta must have shape (n,)")
return scores
def _resolve_scores_many(self, Theta: Array, XTheta: Optional[Array]) -> Array:
if XTheta is None:
return (self._X @ Theta.T).astype(float, copy=False)
scores = np.asarray(XTheta, dtype=float)
if scores.ndim != 2:
raise ValueError("XTheta must have shape (n, k) or (k, n)")
if scores.shape == (Theta.shape[0], self._n):
scores = scores.T
elif scores.shape != (self._n, Theta.shape[0]):
raise ValueError("XTheta must have shape (n, k) or (k, n)")
return scores
# -------------------------------------------------------------- objectives
def objective(self, theta: Array, *, x_theta: Optional[Array] = None) -> float:
theta_arr = self._validate_theta(theta)
scores = self._resolve_scores_single(theta_arr, x_theta)
if self._estimator == "logistic":
data = float(np.mean(self._sw * (np.logaddexp(0.0, scores) - self._y * scores)))
else:
resid = self._y - scores
data = float(0.5 * np.mean(self._sw * resid * resid))
reg = 0.5 * self._lam * float(theta_arr @ (self._reg_mask * theta_arr))
return data + reg
def objective_many(self, Theta: Array, *, XTheta: Optional[Array] = None) -> Array:
Theta_arr = self._validate_thetas(Theta)
scores = self._resolve_scores_many(Theta_arr, XTheta)
if self._estimator == "logistic":
loss_terms = np.logaddexp(0.0, scores) - self._y[:, None] * scores
data = np.mean(self._sw[:, None] * loss_terms, axis=0)
else:
resid = self._y[:, None] - scores
data = 0.5 * np.mean(self._sw[:, None] * resid * resid, axis=0)
reg = 0.5 * self._lam * np.sum(Theta_arr * Theta_arr * self._reg_mask[None, :], axis=1)
return (data + reg).astype(float, copy=False)
def loss_gap(self, theta: Array, *, x_theta: Optional[Array] = None) -> float:
return float(self.objective(theta, x_theta=x_theta) - self._L_hat)
def loss_gap_many(self, Theta: Array, *, XTheta: Optional[Array] = None) -> Array:
return self.objective_many(Theta, XTheta=XTheta) - self._L_hat
def contains(self, theta: Array, *, x_theta: Optional[Array] = None, atol: Optional[float] = None) -> bool:
tol = self._tol if atol is None else float(atol)
return bool(self.loss_gap(theta, x_theta=x_theta) <= self._epsilon + tol)
def contains_many(
self,
Theta: Array,
*,
XTheta: Optional[Array] = None,
atol: Optional[float] = None,
) -> Array:
tol = self._tol if atol is None else float(atol)
gaps = self.loss_gap_many(Theta, XTheta=XTheta)
return gaps <= self._epsilon + tol
[docs]
class RashomonSet:
"""
The Rashomon Set for Generalized Linear Models (GLMs).
The Rashomon set is the set of all models that perform "approximately as well" as the
optimal model, within a user-defined tolerance epsilon. Exploring this set allows
practitioners to understand the **predictive multiplicity** of their problem: the existence
of competing models that make conflicting predictions for the same input.
This class provides a unified interface to:
1. **Define** the Rashomon set via loss-level-set or likelihood ratio calibration.
2. **Sample** from the set using ellipsoidal approximation (fast) or Hit-and-Run MCMC (asymptotically exact).
3. **Audit** stability using coefficient distributions, Model Class Reliance
(Fisher, Rudin, Dominici 2019), and predictive multiplicity metrics
(ambiguity/discrepancy per Marx, Calmon, Ustun 2020).
The coefficient distribution (``variable_importance_cloud``) shows the spread of
each parameter across the Rashomon set. This is inspired by the Variable Importance
Cloud concept of Dong & Rudin (2020) but adapted to the GLM setting where raw
coefficients serve as the natural importance measure (rather than the SHAP-based
importance used in Dong & Rudin's tree-model formulation).
**When to use this:**
- **Regulatory audits**: When you must demonstrate that model conclusions are
robust to the choice of near-optimal model, not just to sampling noise.
- **Feature stability**: To identify features whose importance is an artifact of
the optimizer's particular solution versus a robust property of the data.
- **Prediction robustness**: To flag individuals whose predictions depend on
which equally-good model happens to be selected.
Parameters
----------
estimator : {"logistic", "linear"}
Base GLM family.
reg : {"l2"}
Regularization type (currently L2 only).
C : float
Inverse regularization strength for the *mean-loss* objective
``L(theta) = mean_i loss_i(theta) + (lambda/2) ||theta||^2`` with
``lambda = 1/C``. Use ``C=np.inf`` for an unpenalized fit (lambda=0).
.. warning::
This is **not** scikit-learn's ``C``. scikit-learn minimizes
``C_sk * sum_i loss_i + 0.5 ||w||^2``, so ``C_sk = C / n``
(equivalently ``lambda = 1 / (n * C_sk)``). To audit an existing
scikit-learn model use :func:`rashomon.audit` or
:meth:`RashomonSet.from_sklearn`, which perform the conversion.
epsilon : float
Tolerance parameter.
- If epsilon_mode == "percent_loss": interpreted as rho in (0,1) (percentage of loss increase).
- If epsilon_mode == "LR_alpha": interpreted as alpha in (0,1) (Chi2 significance level).
- If epsilon_mode == "absolute": interpreted as the loss gap itself, in the units of ``L``.
epsilon_mode : {"percent_loss", "LR_alpha", "absolute"}
Calibration mode for epsilon.
fit_intercept : bool
If True, a column of ones is prepended to X internally and the
intercept is included in the Rashomon set analysis. The intercept
coefficient is separated out in ``intercept_`` and excluded from
``coef_``. Default False (no intercept).
penalize_intercept : bool
Only relevant when ``fit_intercept=True``. If False (default, the
scikit-learn convention) the intercept is excluded from the L2 penalty.
If True the intercept is penalized like every other coefficient.
sampler : {"ellipsoid", "hitandrun"}
Sampling backend. "ellipsoid" is faster for lower dimensions; "hitandrun" is more robust
for complex sets or higher dimensions.
measure : {"param", "lr"}
Volume measure choice (annotated in diagnostics only).
random_state : Optional[int]
Random seed for determinism.
max_iter : int
Max iterations for internal solvers when sklearn is unavailable.
tol : float
Convergence tolerance for internal solvers and CG.
safety_override : bool
If True, do not hard-fail on conditioning/separation guardrails.
bootstrap_fallback : bool
If True, use parametric bootstrap calibration for LR_alpha when
Wilks' preconditions are violated (penalized/high-dim).
bootstrap_reps : int
Number of bootstrap replicates for LR_alpha fallback (default 200).
Examples
--------
>>> from rashomon import RashomonSet
>>> import numpy as np
>>> X, y = np.random.randn(100, 5), np.random.randint(0, 2, 100)
>>> rs = RashomonSet(epsilon=0.05)
>>> rs.fit(X, y)
>>> # Check how many predictions flip across the set
>>> amb = rs.ambiguity(X)
>>> print(f"Ambiguity Rate: {amb['ambiguity_rate']:.2%}")
"""
def __init__(
self,
estimator: str = "logistic",
reg: str = "l2",
C: float = 1.0,
epsilon: float = 0.02,
epsilon_mode: str = "percent_loss",
fit_intercept: bool = False,
sampler: str = "ellipsoid",
measure: str = "lr",
random_state: Optional[int] = None,
max_iter: int = 1000,
tol: float = 1e-6,
safety_override: bool = False,
bootstrap_fallback: bool = True,
bootstrap_reps: int = 200,
penalize_intercept: bool = False,
) -> None:
self.estimator = estimator
self.reg = reg
self.C = float(C)
self.epsilon = float(epsilon)
self.epsilon_mode = epsilon_mode
self.fit_intercept = bool(fit_intercept)
self.penalize_intercept = bool(penalize_intercept)
self.sampler = sampler
self.measure = measure
self.random_state = random_state
self.max_iter = int(max_iter)
self.tol = float(tol)
self.safety_override = bool(safety_override)
self.bootstrap_fallback = bool(bootstrap_fallback)
self.bootstrap_reps = int(bootstrap_reps)
self._fitted = False
self._n = 0
self._d = 0
self._d_original = 0 # original feature count (before intercept column)
self._seed = int(random_state) if random_state is not None else None
# Learned state
self._theta_hat: Optional[Array] = None
self._L_hat: Optional[float] = None
self._lambda: Optional[float] = None
self._reg_mask: Optional[Array] = None # 1 = penalized coordinate, 0 = unpenalized
self._sw: Optional[Array] = None # row weights with mean 1
self._kappa_H: Optional[float] = None
self._epsilon_value: Optional[float] = None
self._implied_alpha: Optional[float] = None
# Cached for HVP / membership
self._X: Optional[Array] = None
self._y: Optional[Array] = None
self._w_diag: Optional[Array] = None # Hessian row weights: sw*p(1-p) (logistic) or sw (linear)
self._oracle: Optional[_MembershipOracle] = None
# Cached matrices for performance (D15-D17 optimizations)
self._H: Optional[Array] = None # Hessian matrix
self._H_chol: Optional[Array] = None # Cholesky factorization of H
self._H_inv_diag: Optional[Array] = None # Diagonal of H^{-1} for preconditioning
# Sampling diagnostics (D18)
self._last_sample_diagnostics: Optional[Dict[str, Any]] = None
# ------------------------------ Public API ------------------------------
def _augment_X(self, X: Array) -> Array:
"""Prepend a column of ones for the intercept."""
return np.column_stack([np.ones(X.shape[0], dtype=float), X])
[docs]
def fit(
self,
X: Array,
y: Array,
*,
theta_init: Optional[Array] = None,
sample_weight: Optional[Array] = None,
) -> RashomonSet:
"""Fit the base GLM and prepare diagnostics and operators.
Parameters
----------
X, y : arrays
Training data. For logistic models ``y`` must be in {0, 1}.
theta_init : array of shape (d,) or (d+1,) when ``fit_intercept=True``, optional
Warm start for the solver, e.g. the coefficients of an already-fitted
model (intercept first). The optimum is always polished with damped
Newton steps, so the result does not depend on the warm start beyond
floating-point effects.
sample_weight : array of shape (n,), optional
Non-negative row weights. The data term becomes the weighted mean loss
``sum_i w_i loss_i / sum_i w_i``; the weights are rescaled to mean 1
internally, so only their ratios matter.
Notes
-----
- L(θ) = weighted mean loss + (λ/2) θᵀ M θ, where M masks out unpenalized
coordinates (the intercept unless ``penalize_intercept=True``).
- Guardrails enforce λ ≥ 0 and reasonable conditioning unless overridden.
With λ = 0 (``C=np.inf``) the fit is the unpenalized MLE / OLS and the
Hessian must be positive definite on its own.
- When fit_intercept=True, a column of ones is prepended to X internally.
The intercept is part of the full parameter vector θ and is included in
all Rashomon set computations. Access via ``intercept_`` property.
"""
self._oracle = None
self._H = None
self._H_chol = None
self._H_inv_diag = None
self._last_sample_diagnostics = None
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float)
if X.ndim != 2:
raise ValueError("X must be 2D array")
if y.ndim != 1 or y.shape[0] != X.shape[0]:
raise ValueError("y must be 1D with same n as X")
if self.estimator == "logistic" and not np.all(np.isin(y, (0.0, 1.0))):
raise ValueError("Logistic models require y in {0, 1}")
self._d_original = X.shape[1]
if self.fit_intercept:
X = self._augment_X(X)
n, d = X.shape
self._n, self._d = n, d
if not (self.C > 0.0):
raise ValueError("C must be > 0 (use C=np.inf for an unpenalized fit)")
lam = 0.0 if np.isinf(self.C) else 1.0 / self.C
if self.reg.lower() != "l2":
raise ValueError("Only L2 regularization is supported in v0")
self._lambda = lam
mask = np.ones(d, dtype=float)
if self.fit_intercept and not self.penalize_intercept:
mask[0] = 0.0
self._reg_mask = mask
if theta_init is not None:
theta_init = np.asarray(theta_init, dtype=float).ravel()
if theta_init.shape != (d,):
raise ValueError(f"theta_init must have shape ({d},) including the intercept if fit_intercept=True")
if sample_weight is None:
sw = np.ones(n, dtype=float)
else:
sw = np.asarray(sample_weight, dtype=float).ravel()
if sw.shape != (n,):
raise ValueError(f"sample_weight must have shape ({n},)")
if np.any(sw < 0) or not np.all(np.isfinite(sw)) or not (sw.sum() > 0):
raise ValueError("sample_weight must be finite, non-negative and not all zero")
sw = sw * (n / sw.sum())
self._sw = sw
if self.estimator == "logistic":
theta, L_hat, w_diag = self._fit_logistic_l2(X, y, lam, mask, theta_init=theta_init, sw=sw)
self._w_diag = w_diag
elif self.estimator == "linear":
theta, L_hat = self._fit_linear_ridge(X, y, lam, mask, sw=sw)
self._w_diag = sw.copy()
else:
raise ValueError("estimator must be 'logistic' or 'linear'")
self._theta_hat = theta
self._L_hat = float(L_hat)
self._X = X
self._y = y
# Guardrails: conditioning and separation proxies
kappa_H = self._estimate_hessian_condition_number()
if self.estimator == "logistic":
p_hat = _sigmoid(X @ theta)
pq = p_hat * (1.0 - p_hat)
w_min = float(np.min(pq[sw > 0])) if np.any(sw > 0) else 1.0
else:
w_min = 1.0
# With lambda > 0 the objective is strongly convex and the set bounded, so points
# with tiny p(1-p) are fine. Without a penalty, (quasi-)separation means the MLE
# does not exist, so the fit is rejected.
if self.estimator == "logistic" and lam == 0.0 and w_min < 1e-6 and not self.safety_override:
raise RuntimeError(
"Near-separation detected in an unpenalized logistic fit (min p(1-p) too small); "
"the maximum-likelihood optimum is not finite. Add L2 regularization or override."
)
# Conditioning. Up to ~1e12 double precision still carries several significant
# digits through the Cholesky and Newton solves, so warn; beyond that the Hessian is
# numerically singular (collinear or constant features without a penalty, or
# features on wildly different scales) and the set is not computable.
self._kappa_H = kappa_H
if kappa_H is not None and kappa_H > 1e8 and not self.safety_override:
if kappa_H > 1e12:
raise RuntimeError(
f"The Hessian of the objective is numerically singular (condition number {kappa_H:.1e}). "
"This happens with collinear or constant features in an unpenalized fit, or with features "
"on very different scales. Standardize the features (e.g. a Pipeline with StandardScaler) "
"and refit, or add L2 regularization."
)
warnings.warn(
f"The Hessian is ill-conditioned (condition number {kappa_H:.1e}); results are computed in "
"double precision but standardizing the features would improve numerical accuracy.",
stacklevel=2,
)
# Epsilon calibration
self._epsilon_value, self._implied_alpha = self._calibrate_epsilon()
if self._X is None or self._y is None or self._lambda is None or self._L_hat is None or self._epsilon_value is None:
raise RuntimeError("Model calibration incomplete after fit().")
self._oracle = _MembershipOracle(
estimator=self.estimator,
X=self._X,
y=self._y,
lam=self._lambda,
L_hat=self._L_hat,
epsilon=self._epsilon_value,
tol=self._membership_slack(),
reg_mask=self._reg_mask,
sample_weight=self._sw,
)
self._fitted = True
return self
[docs]
@classmethod
def from_sklearn(
cls, model: Any, X: Array, y: Array, *, sample_weight: Optional[Array] = None, **kwargs: Any
) -> RashomonSet:
"""Build a :class:`RashomonSet` around an already-fitted scikit-learn model.
Supported: ``LogisticRegression`` (binary, L2 or unpenalized, with or without
``class_weight``), ``LogisticRegressionCV``, ``Ridge``, ``RidgeCV``,
``LinearRegression``, and a ``Pipeline`` ending in one of these. The
regularization strength, intercept handling and row weights are converted so
that the audited optimum is the model you fitted.
Parameters
----------
model : fitted estimator
X, y : training data (``X`` may be a pandas DataFrame)
sample_weight : array of shape (n,), optional
The ``sample_weight`` passed to ``model.fit``, if any. ``class_weight`` is
read from the model itself.
**kwargs : forwarded to :class:`RashomonSet` (e.g. ``epsilon``, ``epsilon_mode``,
``random_state``). ``estimator``, ``C``, ``fit_intercept`` and
``penalize_intercept`` are derived from ``model`` and cannot be overridden.
"""
from ._sklearn import rashomon_set_from_sklearn
return rashomon_set_from_sklearn(cls, model, X, y, sample_weight=sample_weight, **kwargs)
[docs]
def diagnostics(self) -> Dict[str, Any]:
if not self._fitted:
raise RuntimeError("Call fit() before diagnostics().")
blas_vendor = _detect_blas_vendor()
diag: Dict[str, Any] = {
"n": self._n,
"d": self._d,
"L_hat": self._L_hat,
"theta_norm_2": float(np.linalg.norm(self._theta_hat)) if self._theta_hat is not None else None,
"epsilon": self._epsilon_value,
"epsilon_mode": self.epsilon_mode,
"lambda": self._lambda,
"penalize_intercept": self.penalize_intercept,
"weighted": bool(self._sw is not None and not np.allclose(self._sw, 1.0)),
"implied_alpha": self._implied_alpha,
"measure": self.measure,
"seed": self._seed,
"blas_vendor": blas_vendor,
"kappa_H_est": self._estimate_hessian_condition_number(),
"min_w_diag": float(np.min(self._w_diag)) if self._w_diag is not None else None,
"min_signed_margin": self._compute_min_signed_margin(),
}
# Add sampling diagnostics if available (D18)
if self._last_sample_diagnostics is not None:
diag.update({
"sampler_diagnostics": self._last_sample_diagnostics,
"set_fidelity": self._last_sample_diagnostics.get("set_fidelity"),
"isotropy_ratio": self._last_sample_diagnostics.get("isotropy_ratio"),
})
else:
diag.update({
"set_fidelity": None,
"isotropy_ratio": None,
})
return diag
[docs]
def hacking_interval(self, s: Array) -> Dict[str, float]:
if not self._fitted:
raise RuntimeError("Call fit() first.")
if self._theta_hat is None or self._epsilon_value is None:
raise RuntimeError("Model not fully initialized.")
s = np.asarray(s)
if s.ndim != 1 or s.shape[0] != self._d:
raise ValueError("s must be a 1D vector of length d")
# s^T theta_hat ± sqrt(2 ε) ||s||_{H^{-1}}
center = float(np.dot(s, self._theta_hat))
hinv_norm = self._hinv_norm(s)
delta = float(np.sqrt(2.0 * self._epsilon_value) * hinv_norm)
return {"min": center - delta, "max": center + delta}
[docs]
def objective(self, theta: Array, *, x_theta: Optional[Array] = None) -> float:
"""Compute penalized objective L(θ) at parameter θ.
L(θ) = average loss + (λ/2)||θ||^2
"""
if not self._fitted:
raise RuntimeError("Call fit() first.")
if self._oracle is None:
raise RuntimeError("Membership oracle not initialized.")
return float(self._oracle.objective(theta, x_theta=x_theta))
[docs]
def loss_gap(self, theta: Array, *, x_theta: Optional[Array] = None) -> float:
"""Return L(θ) - L(θ̂)."""
if self._oracle is None:
raise RuntimeError("Call fit() first.")
return float(self._oracle.loss_gap(theta, x_theta=x_theta))
[docs]
def contains(self, theta: Array, atol: float = 1e-12, *, x_theta: Optional[Array] = None) -> bool:
"""Return True if θ is inside the ε-Rashomon set: L(θ) - L(θ̂) ≤ ε."""
if self._epsilon_value is None:
raise RuntimeError("Call fit() first.")
if self._oracle is None:
raise RuntimeError("Membership oracle not initialized.")
return bool(self._oracle.contains(theta, x_theta=x_theta, atol=float(atol)))
# ---------------------- Vectorized membership (D14) ---------------------
[docs]
def objective_many(self, Theta: Array, *, XTheta: Optional[Array] = None) -> Array:
"""Vectorized penalized objective for a batch of parameters.
Parameters
----------
Theta : array-like of shape (k, d)
Rows are parameter vectors θ_j.
Returns
-------
np.ndarray of shape (k,)
Values L(θ_j) for each row.
"""
if not self._fitted:
raise RuntimeError("Call fit() first.")
if self._oracle is None:
raise RuntimeError("Membership oracle not initialized.")
return self._oracle.objective_many(Theta, XTheta=XTheta)
[docs]
def loss_gap_many(self, Theta: Array, *, XTheta: Optional[Array] = None) -> Array:
"""Vectorized loss gap: L(θ_j) - L(θ̂) for rows of Theta."""
if self._oracle is None:
raise RuntimeError("Call fit() first.")
return self._oracle.loss_gap_many(Theta, XTheta=XTheta)
[docs]
def contains_many(self, Theta: Array, atol: float = 1e-12, *, XTheta: Optional[Array] = None) -> Array:
"""Vectorized membership oracle: return mask of rows inside ε-set.
Returns a boolean array of shape (k,).
"""
if self._epsilon_value is None:
raise RuntimeError("Call fit() first.")
if self._oracle is None:
raise RuntimeError("Membership oracle not initialized.")
return self._oracle.contains_many(Theta, XTheta=XTheta, atol=float(atol))
# --------------------------- Predictive API ----------------------------
def _prepare_X(self, X: Array) -> Array:
"""Validate and augment X for prediction/analysis methods."""
X = np.asarray(X)
if self.fit_intercept:
if X.ndim != 2 or X.shape[1] != self._d_original:
raise ValueError(f"X must be 2D with {self._d_original} features")
return self._augment_X(X)
if X.ndim != 2 or X.shape[1] != self._d:
raise ValueError(f"X must be 2D with {self._d} features")
return X
[docs]
def decision_function(self, X: Array) -> Array:
if not self._fitted or self._theta_hat is None:
raise RuntimeError("Call fit() first.")
X = self._prepare_X(X)
return (X @ self._theta_hat).astype(float, copy=False)
[docs]
def predict_proba(self, X: Array) -> Array:
if self.estimator != "logistic":
raise NotImplementedError("predict_proba is only defined for logistic models")
scores = self.decision_function(X)
p = _sigmoid(scores)
return np.vstack([1.0 - p, p]).T
[docs]
def predict(self, X: Array) -> Array:
scores = self.decision_function(X)
if self.estimator == "logistic":
return (scores > 0.0).astype(int)
return scores
[docs]
def probability_bands(self, X: Array) -> Array:
"""Per-sample probability bands for logistic models via hacking intervals.
For each row x, computes the tight interval [p_min, p_max] where
p_min = sigma(z_min), p_max = sigma(z_max), and [z_min, z_max] is the
hacking interval of s := x in margin space. Since sigma is monotone,
applying it directly to the margin extrema gives the exact probability
bounds over the ellipsoidal Rashomon set (no Lipschitz relaxation needed).
Returns an array of shape (n, 2) with columns [p_min, p_max].
"""
if self.estimator != "logistic":
raise NotImplementedError("probability_bands is only defined for logistic models")
if not self._fitted:
raise RuntimeError("Call fit() first.")
X = self._prepare_X(X)
out = np.empty((X.shape[0], 2), dtype=float)
for i in range(X.shape[0]):
s = X[i]
interval = self.hacking_interval(s)
zmin, zmax = interval["min"], interval["max"]
pmin, pmax = float(_sigmoid(zmin)), float(_sigmoid(zmax))
# Ensure ordering in case of numerical edge equality
if pmin > pmax:
pmin, pmax = pmax, pmin
out[i, 0] = pmin
out[i, 1] = pmax
return out
# ---------------------- VIC-style coefficient intervals -----------------
[docs]
def coef_intervals(self, indices: Optional[Array] = None) -> Array:
"""Coefficient-wise intervals under the ellipsoid certificate.
For each selected coordinate j, returns [min_j, max_j] where
min_j,max_j are the hacking interval for s=e_j.
Parameters
----------
indices : Optional[array-like]
Indices of coefficients to compute. If None, compute all.
Returns
-------
np.ndarray of shape (m, 2)
Interval bounds for selected m coordinates in the order given.
"""
if not self._fitted:
raise RuntimeError("Call fit() first.")
d = self._d
idx: Array
if indices is None:
idx = np.arange(d)
else:
idx = np.asarray(indices, dtype=int)
if idx.ndim != 1:
raise ValueError("indices must be 1D")
if np.any((idx < 0) | (idx >= d)):
raise ValueError("indices out of range")
out = np.empty((idx.shape[0], 2), dtype=float)
for k, j in enumerate(idx):
e = np.zeros(d, dtype=float)
e[j] = 1.0
iv = self.hacking_interval(e)
out[k, 0] = iv["min"]
out[k, 1] = iv["max"]
return out
[docs]
def quadratic_error(self, S: Optional[Array] = None, method: str = "ray", steps: int = 1) -> Array:
"""How far the exact range of ``sᵀθ`` departs from the Hessian ellipsoid's, estimated
without the full convex program.
The ellipsoid gives ``sᵀθ̂ ± r‖s‖_{H⁻¹}`` with ``r = sqrt(2ε)``, attained at
``θ̂ ± r u`` with ``u = H⁻¹s / ‖s‖_{H⁻¹}``. Along that ray the true loss
``L(θ̂ + t u)`` is convex in ``t`` with ``L(θ̂ + t u) = L̂ + t²/2 + O(t³)``, so the
ellipsoid is exact when the loss is quadratic along the ray and otherwise its
boundary is at the ``t`` on each side where ``L(θ̂ + t u) = L̂ + ε``.
``method="ray"`` finds those two roots on the true loss (one-dimensional
bisection, ``O(n)`` per evaluation). Because the boundary points lie in the set,
the resulting half-ranges are inner bounds on the exact ones: the exact range is
at least as wide on each side, and wider only when the set's extreme point for
``s`` is off the ray.
``method="newton"`` starts from the ray boundary point and takes ``steps`` steps
of the exact program's own iteration: with ``g`` and ``H₀`` the gradient and
Hessian there, ``a = H₀⁻¹s``, ``b = H₀⁻¹g`` and ``μ = sqrt(gᵀb / sᵀa)``, the step
``δ = μa − b`` solves the linearized conditions ``∇L = μs`` on the level set, and by
Cauchy–Schwarz ``gᵀδ ≤ 0``, so the loss first falls along ``δ`` and the point where
it returns to ``L̂ + ε`` is in the set. The result is still an inner bound, now
with the set's curvature at the boundary; one step costs one Hessian build per
functional (``O(n d²)``), against the dozens of the exact program.
``method="quartic"`` uses the Taylor expansion of the loss along the ray to
fourth order, ``T = (1/n) Σ sw_i ψ'''(z_i)(x_iᵀu)³`` and
``Q = (1/n) Σ sw_i ψ''''(z_i)(x_iᵀu)⁴`` with ``ψ''' = p(1-p)(1-2p)`` and
``ψ'''' = p(1-p)(1-6p(1-p))``. It is a closed form, is not a bound, and fails
when a direction is dominated by few rows; it is kept for the evaluation.
Parameters
----------
S : array of shape (m, d), optional
Functionals, one per row, in the internal layout (intercept first if fitted).
Default: the ``d`` coordinate vectors, i.e. the coefficients themselves.
method : {"ray", "newton", "quartic"}
steps : int
Newton steps for ``method="newton"`` (default 1).
Returns
-------
np.ndarray of shape (m, 2)
The relative deviation of the lower and upper half-ranges from the ellipsoid
half-range ``r‖s‖_{H⁻¹}``. 0 means the ellipsoid is exact there; ``inf``
means the loss never reaches ``L̂ + ε`` on that side (a direction of
recession, possible only without a penalty). Always 0 for linear models,
whose loss is quadratic.
"""
if not self._fitted or self._theta_hat is None or self._epsilon_value is None or self._X is None:
raise RuntimeError("Call fit() first.")
if method not in ("ray", "newton", "quartic"):
raise ValueError("method must be 'ray', 'newton' or 'quartic'")
d = self._d
S_arr = np.eye(d) if S is None else np.asarray(S, dtype=float)
if S_arr.ndim == 1:
S_arr = S_arr[None, :]
if S_arr.ndim != 2 or S_arr.shape[1] != d:
raise ValueError(f"S must have shape (m, {d})")
m = S_arr.shape[0]
eps = float(self._epsilon_value)
r = np.sqrt(2.0 * eps)
out = np.zeros((m, 2), dtype=float)
if self.estimator != "logistic":
return out
X, y, theta = self._X, self._y, self._theta_hat
assert y is not None
sw = self._sw_or_ones()
lam = float(self._lambda or 0.0)
mask = self._reg_mask_or_ones()
z = X @ theta
p = _sigmoid(z)
w3 = sw * p * (1.0 - p) * (1.0 - 2.0 * p)
w4 = sw * p * (1.0 - p) * (1.0 - 6.0 * p * (1.0 - p))
chunk = max(1, int(2e7 // max(self._n, 1)))
for start in range(0, m, chunk):
Sc = S_arr[start:start + chunk]
U = self._hinv(Sc.T) # (d, k): H^{-1} s
norms = np.sqrt(np.maximum(np.sum(Sc.T * U, axis=0), 1e-300))
U = U / norms[None, :]
Z = X @ U # (n, k): x_i^T u
for side, col in ((-1.0, 0), (1.0, 1)):
if method == "quartic":
T = (w3 @ Z**3) / self._n
Q = (w4 @ Z**4) / self._n
tau = _quartic_level_root(side * T, Q, eps, r)
else:
# penalty along the ray: lam * t * u'M theta + lam/2 * t^2 * u'Mu
pen_lin = side * lam * (U * (mask * theta)[:, None]).sum(axis=0)
pen_quad = 0.5 * lam * (mask[:, None] * U * U).sum(axis=0)
tau = _logistic_ray_root(z, side * Z, y, sw, pen_lin, pen_quad, eps, r)
dev = np.where(np.isfinite(tau), tau / r - 1.0, np.inf)
if method == "newton":
assert self._L_hat is not None
target = float(self._L_hat) + eps
for k in np.flatnonzero(np.isfinite(tau)):
s = side * Sc[k]
theta_k = self._newton_inner_point(s, theta + side * tau[k] * U[:, k], target, steps)
dev[k] = float(s @ (theta_k - theta)) / (r * norms[k]) - 1.0
out[start:start + chunk, col] = dev
return out
def _newton_inner_point(self, s: Array, theta0: Array, target: float, steps: int) -> Array:
"""From a boundary point ``theta0`` (``L = target``), move toward ``max sᵀθ`` on the set.
Each step linearizes ``∇L(θ) = μ s`` at the current point and returns to the level set
along the step direction by bisection, so the result is in the set (up to the loss
tolerance) and ``sᵀθ`` does not decrease. See :meth:`quadratic_error`.
"""
X, y, sw = self._X, self._y, self._sw_or_ones()
assert X is not None and y is not None
lam, mask, n = float(self._lambda or 0.0), self._reg_mask_or_ones(), self._n
th = theta0
for _ in range(max(int(steps), 0)):
p = _sigmoid(X @ th)
g = X.T @ (sw * (p - y)) / n + lam * mask * th
w = sw * p * (1.0 - p)
H0 = (X * w[:, None]).T @ X / n + lam * np.diag(mask)
try:
L0 = np.linalg.cholesky(H0)
except np.linalg.LinAlgError:
break
a = np.linalg.solve(L0.T, np.linalg.solve(L0, s))
b = np.linalg.solve(L0.T, np.linalg.solve(L0, g))
mu2 = float(g @ b) / max(float(s @ a), 1e-300)
if mu2 <= 0.0:
break
delta = np.sqrt(mu2) * a - b
if float(s @ delta) <= 0.0:
break
lo, hi = 0.0, 1.0
while self.objective(th + hi * delta) <= target and hi < 1024.0:
hi *= 2.0
if self.objective(th + hi * delta) <= target:
th = th + hi * delta # the loss never returns to the level along delta: take the far point
continue
for _ in range(50):
mid = 0.5 * (lo + hi)
if self.objective(th + mid * delta) <= target:
lo = mid
else:
hi = mid
th = th + lo * delta
return th
# -------------------------- Ellipsoid sampler ---------------------------
def _hessian_matrix(self, force_recompute: bool = False) -> Array:
"""Compute or retrieve cached Hessian matrix.
Parameters
----------
force_recompute : bool
If True, recompute even if cached.
"""
if not force_recompute and self._H is not None:
return self._H
if self._X is None or self._lambda is None:
raise RuntimeError("Fit before requesting Hessian")
X = self._X
n = self._n
lam = self._lambda
reg = lam * np.diag(self._reg_mask_or_ones())
if self._w_diag is None:
raise RuntimeError("Weights unavailable")
# _w_diag holds the Hessian row weights: sw * p(1-p) (logistic) or sw (linear).
Xw = X * np.sqrt(self._w_diag)[:, None]
H = (Xw.T @ Xw) / n + reg
self._H = H.astype(float, copy=False)
return self._H
def _reg_mask_or_ones(self) -> Array:
return np.ones(self._d, dtype=float) if self._reg_mask is None else self._reg_mask
def _coordinate_names(self, feature_names: Optional[Sequence[str]]) -> List[str]:
"""Names for all ``d`` coordinates in internal layout (intercept first if fitted).
``feature_names`` may name the features only (length ``d_original``), in which
case ``"(intercept)"`` is prepended, or all coordinates (length ``d``).
"""
n_feat = self._d_original if self.fit_intercept else self._d
if feature_names is None:
names = [f"feature_{i}" for i in range(n_feat)]
else:
names = [str(s) for s in feature_names]
if self.fit_intercept and len(names) == self._d:
return names
if len(names) != n_feat:
raise ValueError(
f"feature_names must have length {n_feat} (the features) or {self._d} (features with the intercept)"
if self.fit_intercept else f"feature_names must have length d={self._d}"
)
return ["(intercept)"] + names if self.fit_intercept else names
def _membership_slack(self) -> float:
"""Floating-point slack for membership tests: ``tol``, but never more than 0.1% of ε.
An absolute slack would swamp a very small tolerance (ε of 1e-10 against
tol of 1e-6 would inflate the set ten-thousand-fold), so it is capped relative
to ε.
"""
eps = float(self._epsilon_value) if self._epsilon_value is not None else float(self.tol)
return float(min(self.tol, 1e-3 * eps))
def _hessian_cholesky(self, force_recompute: bool = False) -> Array:
"""Compute or retrieve cached Cholesky factorization of Hessian.
Returns L where H = L L^T.
"""
if not force_recompute and self._H_chol is not None:
return self._H_chol
H = self._hessian_matrix(force_recompute=force_recompute)
jitter = 0.0
for _ in range(3):
try:
L = np.linalg.cholesky(H + jitter * np.eye(self._d))
self._H_chol = L
return L
except np.linalg.LinAlgError:
jitter = 1e-10 if jitter == 0.0 else jitter * 10.0
raise RuntimeError("Hessian not SPD even with jitter")
[docs]
def sample(self, n_samples: int = 100, **kwargs: Any) -> Array:
"""Sample parameters using the configured sampler backend."""
backend = self.sampler.lower()
if backend == "ellipsoid":
if kwargs:
return self.sample_ellipsoid(n_samples=n_samples, **kwargs)
return self.sample_ellipsoid(n_samples=n_samples)
if backend == "hitandrun":
return self.sample_hitandrun(n_samples=n_samples, **kwargs)
raise ValueError("Unknown sampler. Use 'ellipsoid' or 'hitandrun'.")
[docs]
def sample_ellipsoid(self, n_samples: int = 100, random_state: Optional[int] = None) -> Array:
"""Sample uniformly from the ellipsoid (θ-θ̂)^T H (θ-θ̂) ≤ 2ε.
Uses cached Cholesky factorization H=L L^T and maps a uniform point in the
L2 unit ball via θ = θ̂ + L^{-1} (sqrt(2ε) r u), with u unit vector,
r ~ U(0,1)^{1/d} for uniform-in-ball radius.
Optimized with cached factorization (D15-D17).
"""
if not self._fitted:
raise RuntimeError("Call fit() first.")
if self._theta_hat is None or self._epsilon_value is None:
raise RuntimeError("Model not fully initialized.")
if n_samples <= 0:
raise ValueError("n_samples must be positive")
seed = self._seed if random_state is None else int(random_state)
rng = np.random.default_rng(seed)
return self._ellipsoid_points(rng, n_samples)
def _ellipsoid_points(self, rng: np.random.Generator, k: int) -> Array:
"""k points uniform in {θ : (θ-θ̂)ᵀ H (θ-θ̂) ≤ 2ε}, using the cached Cholesky factor."""
if self._theta_hat is None or self._epsilon_value is None:
raise RuntimeError("Model not fully initialized.")
d = self._d
L = self._hessian_cholesky()
scale = float(np.sqrt(2.0 * self._epsilon_value))
gaussians = rng.normal(size=(k, d))
norms = np.linalg.norm(gaussians, axis=1, keepdims=True)
unit_vecs = gaussians / (norms + 1e-18)
radii = rng.random(k) ** (1.0 / d)
scaled_vecs = scale * radii[:, None] * unit_vecs
# θ = θ̂ + L^{-T} y maps the ball of radius sqrt(2ε) onto the ellipsoid:
# (L^{-T} y)ᵀ H (L^{-T} y) = yᵀ L^{-1} L Lᵀ L^{-T} y = ||y||².
if _HAS_SCIPY:
Z = solve_triangular(L.T, scaled_vecs.T, lower=False).T
else:
Z = np.linalg.solve(L.T, scaled_vecs.T).T
return self._theta_hat[None, :] + Z
def _in_hessian_ellipsoid(self, theta: Array) -> bool:
"""Whether (θ-θ̂)ᵀ H (θ-θ̂) ≤ 2ε."""
if self._theta_hat is None or self._epsilon_value is None:
raise RuntimeError("Model not fully initialized.")
L = self._hessian_cholesky()
w = L.T @ (theta - self._theta_hat)
return bool(w @ w <= 2.0 * self._epsilon_value)
[docs]
def sample_hitandrun(
self,
n_samples: int = 100,
*,
burnin: int = 200,
thin: int = 1,
directions: Optional[str] = None,
precondition: Optional[bool] = None,
t_init: float = 1.0,
growth: float = 2.0,
max_bracket: float = 1e6,
max_bisect: int = 50,
tol: float = 1e-10,
random_state: Optional[int] = None,
compute_diagnostics: bool = True,
ellipsoid_mix: float = 0.0,
) -> Array:
"""Hit-and-Run sampling using bracketed line search with safeguards.
Targets the uniform distribution on the exact ε-Rashomon set (membership
oracle), so samples are not restricted to the Hessian ellipsoid.
Parameters
----------
ellipsoid_mix : float in [0, 1)
Probability, at each step, of replacing the hit-and-run move by an
independence proposal drawn uniformly from the Hessian ellipsoid
``(θ-θ̂)ᵀH(θ-θ̂) ≤ 2ε``. The proposal is accepted iff it lies in the
Rashomon set and the current point lies in the ellipsoid. This is the
Metropolis-Hastings ratio for a uniform target, so the chain still
targets the uniform law on the true set. In low to moderate dimension
most of the ellipsoid lies inside the set, most proposals are accepted,
and the effective sample size per step improves by about a factor of d
over plain hit-and-run. In high dimension proposals are rarely accepted
and the chain behaves like plain hit-and-run. Default 0 (plain
hit-and-run).
"""
if not self._fitted or self._theta_hat is None:
raise RuntimeError("Call fit() first.")
if self._oracle is None or self._X is None or self._y is None or self._epsilon_value is None:
raise RuntimeError("Model not fully initialized.")
if n_samples <= 0:
raise ValueError("n_samples must be positive")
if burnin < 0:
raise ValueError("burnin must be non-negative")
if thin <= 0:
raise ValueError("thin must be positive")
if t_init <= 0.0:
raise ValueError("t_init must be positive")
if growth <= 1.0:
raise ValueError("growth must be > 1.0")
if max_bracket <= 0.0:
raise ValueError("max_bracket must be positive")
if not (0.0 <= ellipsoid_mix < 1.0):
raise ValueError("ellipsoid_mix must be in [0, 1)")
if ellipsoid_mix > 0.0:
try:
self._hessian_cholesky()
except RuntimeError:
warnings.warn("Hessian is not numerically SPD; ellipsoid proposals disabled.", stacklevel=2)
ellipsoid_mix = 0.0
if directions is None:
dir_mode = "whitened" if self.measure == "lr" else "euclidean"
else:
dir_mode = directions.lower()
if dir_mode not in {"whitened", "euclidean"}:
raise ValueError("directions must be 'whitened' or 'euclidean'")
if precondition is None:
use_precondition = dir_mode == "whitened"
else:
use_precondition = bool(precondition)
oracle = self._oracle
eps = float(self._epsilon_value)
theta = self._theta_hat.copy()
z = self._X @ theta
seed = self._seed if random_state is None else int(random_state)
rng = np.random.default_rng(seed)
total_steps = burnin + n_samples * max(1, thin)
max_steps = max(total_steps * 20, total_steps + 1)
samples = np.empty((n_samples, self._d), dtype=float)
saved = 0
step = 0
line_tol = float(tol)
max_growth_steps = 64
def make_delta(direction: Array, direction_proj: Array) -> Callable[[float], float]:
def _delta(t: float) -> float:
theta_t = theta + t * direction
z_t = z + t * direction_proj
return float(oracle.loss_gap(theta_t, x_theta=z_t) - eps)
return _delta
def bracket_limit(direction: Array, direction_proj: Array) -> Optional[float]:
delta_fn = make_delta(direction, direction_proj)
delta_inside = delta_fn(0.0)
t = float(t_init)
delta_outside = delta_fn(t)
growth_steps = 0
while delta_outside <= line_tol and abs(t) < max_bracket and growth_steps < max_growth_steps:
t *= growth
delta_outside = delta_fn(t)
growth_steps += 1
if delta_outside <= line_tol:
return None
inside_val = 0.0
outside_val = t
f_inside = delta_inside
f_outside = delta_outside
for _ in range(max_bisect):
if abs(f_outside - f_inside) > 1e-18:
cand = outside_val - f_outside * (outside_val - inside_val) / (f_outside - f_inside)
else:
cand = 0.5 * (outside_val + inside_val)
if not np.isfinite(cand):
cand = 0.5 * (outside_val + inside_val)
low, high = (inside_val, outside_val) if inside_val < outside_val else (outside_val, inside_val)
if not (low < cand < high):
cand = 0.5 * (outside_val + inside_val)
delta_cand = delta_fn(cand)
if delta_cand > 0.0:
outside_val = cand
f_outside = delta_cand
else:
inside_val = cand
f_inside = delta_cand
if abs(outside_val - inside_val) <= max(line_tol, 1e-12 * max(1.0, abs(inside_val))):
break
return inside_val
cur_in_ellipsoid = True # the chain starts at θ̂
n_proposals = 0
n_accepted = 0
while saved < n_samples:
if step >= max_steps:
raise RuntimeError(
"Hit-and-run could not find chords through the Rashomon set within the step cap. "
f"The set is probably too small to resolve numerically (epsilon={eps:.3g} against an "
f"optimal loss of {float(self._L_hat or 0.0):.3g}); increase the tolerance."
)
step += 1
if ellipsoid_mix > 0.0 and rng.random() < ellipsoid_mix:
# Independence proposal from the Hessian ellipsoid (see docstring).
n_proposals += 1
proposal = self._ellipsoid_points(rng, 1)[0]
if cur_in_ellipsoid and oracle.contains(proposal):
theta = proposal
z = self._X @ theta
n_accepted += 1
if step > burnin and ((step - burnin) % max(1, thin) == 0):
samples[saved] = theta
saved += 1
continue
g = rng.normal(size=self._d)
if use_precondition:
# Direction ~ N(0, H^{-1}) via the cached Cholesky factor: v = L^{-T} g.
# Any centrally symmetric, full-support direction law keeps the uniform
# law stationary; matching the local Hessian geometry improves mixing.
v = self._whiten_direction(g)
else:
v = g
norm_v = float(np.linalg.norm(v))
if norm_v < 1e-12:
continue
v = v / norm_v
xv = self._X @ v
limit_pos = bracket_limit(v, xv)
if limit_pos is None or limit_pos <= 0.0:
continue
limit_neg_pos = bracket_limit(-v, -xv)
if limit_neg_pos is None or limit_neg_pos <= 0.0:
continue
t_plus = limit_pos
t_minus = -limit_neg_pos
if not np.isfinite(t_plus) or not np.isfinite(t_minus) or t_plus <= t_minus:
continue
t = float(rng.uniform(t_minus, t_plus))
theta = theta + t * v
z = z + t * xv
if ellipsoid_mix > 0.0:
cur_in_ellipsoid = self._in_hessian_ellipsoid(theta)
if step > burnin and ((step - burnin) % max(1, thin) == 0):
samples[saved] = theta
saved += 1
# Compute and cache diagnostics (D18)
if compute_diagnostics:
self._last_sample_diagnostics = self.compute_sample_diagnostics(
samples, burnin=0, compute_ess=True, compute_isotropy=True
)
if ellipsoid_mix > 0.0:
self._last_sample_diagnostics["ellipsoid_proposals"] = n_proposals
self._last_sample_diagnostics["ellipsoid_acceptance"] = (
n_accepted / n_proposals if n_proposals else None
)
return samples
# --------------------------- Sklearn-style attrs -----------------------
@property
def coef_(self) -> Array:
if not self._fitted or self._theta_hat is None:
raise RuntimeError("Call fit() first.")
if self.fit_intercept:
return self._theta_hat[1:]
return self._theta_hat
@property
def intercept_(self) -> float:
"""Intercept term (0.0 if fit_intercept=False)."""
if not self._fitted or self._theta_hat is None:
raise RuntimeError("Call fit() first.")
if self.fit_intercept:
return float(self._theta_hat[0])
return 0.0
@property
def n_features_in_(self) -> int:
if not self._fitted:
raise RuntimeError("Call fit() first.")
return int(self._d_original) if self.fit_intercept else int(self._d)
# --------------------------- Sklearn-style utils ------------------------
[docs]
def get_params(self, deep: bool = True) -> Dict[str, Any]:
return {
"estimator": self.estimator,
"reg": self.reg,
"C": self.C,
"epsilon": self.epsilon,
"epsilon_mode": self.epsilon_mode,
"fit_intercept": self.fit_intercept,
"penalize_intercept": self.penalize_intercept,
"sampler": self.sampler,
"measure": self.measure,
"random_state": self.random_state,
"max_iter": self.max_iter,
"tol": self.tol,
"safety_override": self.safety_override,
"bootstrap_fallback": getattr(self, "bootstrap_fallback", True),
"bootstrap_reps": getattr(self, "bootstrap_reps", 200),
}
[docs]
def set_params(self, **params: Any) -> RashomonSet:
for key, value in params.items():
if not hasattr(self, key):
raise ValueError(f"Unknown parameter: {key}")
setattr(self, key, value)
return self
[docs]
def score(self, X: Array, y: Array) -> float:
"""Sklearn-style score: accuracy (logistic) or R^2 (linear)."""
if not self._fitted:
raise RuntimeError("Call fit() first.")
X = np.asarray(X)
y = np.asarray(y)
if self.estimator == "logistic":
y_pred = self.predict(X)
# y may be float {0,1}; convert to int
return float(np.mean((y_pred == y.astype(int)).astype(float)))
# linear: R^2
y_pred = self.predict(X)
ss_res = float(np.sum((y - y_pred) ** 2))
y_mean = float(np.mean(y))
ss_tot = float(np.sum((y - y_mean) ** 2))
if ss_tot <= 0:
return 1.0 if ss_res <= 0 else 0.0
return 1.0 - ss_res / ss_tot
# ------------------------------ Internals -------------------------------
def _fit_linear_ridge(
self, X: Array, y: Array, lam: float, mask: Optional[Array] = None, sw: Optional[Array] = None
) -> Tuple[Array, float]:
"""Exact minimizer of 0.5*mean(sw*(y - Xθ)^2) + (λ/2) θᵀ diag(mask) θ."""
n, d = X.shape
m = np.ones(d, dtype=float) if mask is None else mask
w = np.ones(n, dtype=float) if sw is None else sw
A = (X.T @ (X * w[:, None])) / n + lam * np.diag(m)
b = (X.T @ (w * y)) / n
try:
theta = np.linalg.solve(A, b)
except np.linalg.LinAlgError:
theta = np.linalg.lstsq(A, b, rcond=None)[0]
resid = y - X @ theta
L = 0.5 * float(np.mean(w * resid**2)) + 0.5 * lam * float(theta @ (m * theta))
return theta, L
def _fit_logistic_l2(
self,
X: Array,
y: Array,
lam: float,
mask: Optional[Array] = None,
*,
theta_init: Optional[Array] = None,
sw: Optional[Array] = None,
) -> Tuple[Array, float, Array]:
"""Minimize mean(sw * logistic loss) + (λ/2) θᵀ diag(mask) θ.
scikit-learn's L-BFGS is used as an initializer when available (and no
warm start is given). The solution is then polished with damped Newton
steps on the exact objective, so ``theta_hat`` is the minimizer rather than
an L-BFGS iterate stopped at sklearn's default tolerance. Returns the
Hessian row weights ``sw * p * (1 - p)`` as the third element.
"""
n, d = X.shape
m = np.ones(d, dtype=float) if mask is None else mask
w = np.ones(n, dtype=float) if sw is None else sw
if theta_init is not None:
theta = np.array(theta_init, dtype=float)
elif _HAS_SK and lam > 0.0:
# sklearn minimizes C*sum(w_i*loss_i) + (1/2)||w||^2 (sum, not mean).
# Our objective: (1/n)*sum(w_i*loss_i) + (lam/2)||w||^2 with mean(w) = 1,
# so C = 1/(n*lam).
unpenalized_intercept = bool(self.fit_intercept and m[0] == 0.0)
model = LogisticRegression(
C=1.0 / (n * lam), fit_intercept=unpenalized_intercept, solver="lbfgs",
max_iter=self.max_iter, random_state=self.random_state,
)
if unpenalized_intercept:
model.fit(X[:, 1:], y.astype(int), sample_weight=w)
theta = np.concatenate([np.ravel(model.intercept_), model.coef_.ravel()]).astype(float)
else:
model.fit(X, y.astype(int), sample_weight=w)
theta = model.coef_.ravel().astype(float, copy=False)
else:
theta = np.zeros(d, dtype=float)
theta = self._newton_logistic(X, y, theta, lam, m, sw=w)
z = X @ theta
p = _sigmoid(z)
w_diag = w * p * (1.0 - p)
L = self._logistic_loss(X, y, theta, lam, m, w)
return theta, L, w_diag
def _newton_logistic(
self,
X: Array,
y: Array,
theta: Array,
lam: float,
mask: Array,
shift: Optional[Array] = None,
sw: Optional[Array] = None,
) -> Array:
"""Damped Newton iterations with Armijo backtracking on the logistic objective.
If ``shift`` is given, minimizes ``L(θ) - shiftᵀθ`` instead (used to trace the
boundary of the Rashomon set in :meth:`functional_range`).
"""
n, d = X.shape
gtol = min(self.tol, 1e-8)
w_rows = np.ones(n, dtype=float) if sw is None else sw
def obj(th: Array) -> float:
val = self._logistic_loss(X, y, th, lam, mask, w_rows)
return val - float(shift @ th) if shift is not None else val
L_curr = obj(theta)
for _ in range(100):
p = _sigmoid(X @ theta)
g = (X.T @ (w_rows * (p - y))) / n + lam * mask * theta
if shift is not None:
g = g - shift
if float(np.linalg.norm(g)) <= gtol:
break
w = w_rows * p * (1.0 - p)
H = (X.T @ (X * w[:, None])) / n + lam * np.diag(mask)
try:
step = np.linalg.solve(H + 1e-12 * np.eye(d), g)
except np.linalg.LinAlgError:
step = g
t = 1.0
slope = float(g @ step)
accepted = False
while t > 1e-10:
theta_new = theta - t * step
L_new = obj(theta_new)
if L_new <= L_curr - 1e-4 * t * slope:
accepted = True
break
t *= 0.5
if not accepted:
break
theta, L_curr = theta_new, L_new
return theta
# ------------------------ Exact extremes over the true set ---------------
[docs]
def functional_range(self, s: Array) -> Tuple[float, float]:
"""Exact ``(min, max)`` of the linear functional ``sᵀθ`` over the ε-Rashomon set.
Solves the convex program ``max sᵀθ s.t. L(θ) ≤ L(θ̂) + ε`` (and the
corresponding min). :meth:`hacking_interval` uses the Hessian ellipsoid
instead, and sampled extremes understate the range. For linear models the
set is the ellipsoid, so the closed form is returned. For logistic models the
maximizer is ``θ(μ) = argmin L(θ) - μ sᵀθ`` for the unique ``μ > 0`` at which
``L(θ(μ)) = L(θ̂) + ε``; ``μ`` is found by safeguarded root finding with
warm-started Newton solves. The cost is a few dozen Hessian builds.
"""
if not self._fitted or self._theta_hat is None or self._epsilon_value is None or self._L_hat is None:
raise RuntimeError("Call fit() first.")
s = np.asarray(s, dtype=float)
if s.ndim != 1 or s.shape[0] != self._d:
raise ValueError("s must be a 1D vector of length d")
if self.estimator == "linear":
iv = self.hacking_interval(s)
return float(iv["min"]), float(iv["max"])
hi = self._maximize_functional(s)
lo = -self._maximize_functional(-s)
return min(lo, hi), max(lo, hi)
def _maximize_functional(self, s: Array) -> float:
"""max sᵀθ over the logistic Rashomon set via the Lagrangian boundary trace."""
assert self._X is not None and self._y is not None and self._theta_hat is not None
assert self._lambda is not None and self._epsilon_value is not None and self._L_hat is not None
X, y, lam, mask = self._X, self._y, float(self._lambda), self._reg_mask_or_ones()
eps, target = float(self._epsilon_value), float(self._L_hat) + float(self._epsilon_value)
theta_hat = self._theta_hat
L = self._hessian_cholesky()
# Quadratic-approximation initial guess: θ(μ) ≈ θ̂ + μ H⁻¹s and L - L̂ ≈ ½μ² sᵀH⁻¹s.
if _HAS_SCIPY:
hinv_s = solve_triangular(L.T, solve_triangular(L, s, lower=True), lower=False)
else:
hinv_s = np.linalg.solve(L.T, np.linalg.solve(L, s))
quad = float(s @ hinv_s)
if quad <= 0.0:
return float(s @ theta_hat)
mu0 = float(np.sqrt(2.0 * eps / quad))
sw = self._sw_or_ones()
def solve_at(mu: float, init: Array) -> Tuple[Array, float]:
th = self._newton_logistic(X, y, init, lam, mask, shift=mu * s, sw=sw)
return th, self._logistic_loss(X, y, th, lam, mask, sw) - target
# Bracket the root of h(μ) = L(θ(μ)) - target, which is increasing in μ.
mu_lo, h_lo, th_lo = 0.0, -eps, theta_hat
mu_hi, th_hi = mu0, theta_hat + mu0 * hinv_s
th_hi, h_hi = solve_at(mu_hi, th_hi)
for _ in range(60):
if h_hi >= 0.0:
break
mu_lo, h_lo, th_lo = mu_hi, h_hi, th_hi
mu_hi *= 2.0
th_hi, h_hi = solve_at(mu_hi, th_hi)
else:
warnings.warn("functional_range: could not bracket the set boundary; returning best lower estimate", stacklevel=2)
return float(s @ th_hi)
# Illinois (modified regula falsi) iterations on the bracket.
tol_h = 1e-10 * max(1.0, abs(target))
best_theta = th_hi
side = 0
for _ in range(80):
if abs(h_hi) <= tol_h:
best_theta = th_hi
break
if abs(h_lo) <= tol_h and mu_lo > 0.0:
best_theta = th_lo
break
mu = mu_hi - h_hi * (mu_hi - mu_lo) / (h_hi - h_lo)
if not (mu_lo < mu < mu_hi):
mu = 0.5 * (mu_lo + mu_hi)
th, h = solve_at(mu, th_lo if abs(h_lo) < abs(h_hi) else th_hi)
if h >= 0.0:
mu_hi, h_hi, th_hi = mu, h, th
if side == -1:
h_lo *= 0.5
side = -1
else:
mu_lo, h_lo, th_lo = mu, h, th
if side == 1:
h_hi *= 0.5
side = 1
best_theta = th_hi
if mu_hi - mu_lo <= 1e-12 * max(1.0, mu_hi):
break
return float(s @ best_theta)
def _hinv(self, V: Array) -> Array:
"""``H⁻¹ V`` through the cached Cholesky factor (``V`` of shape (d,) or (d, m))."""
L = self._hessian_cholesky()
if _HAS_SCIPY:
return np.asarray(solve_triangular(L.T, solve_triangular(L, V, lower=True), lower=False), dtype=float)
return np.linalg.solve(L.T, np.linalg.solve(L, V))
[docs]
def min_loss_on_hyperplane(self, s: Array, c: float, theta0: Optional[Array] = None) -> float:
"""Exact ``min L(θ)`` subject to ``sᵀθ = c``.
Used to decide whether a prediction can cross a threshold: for a row ``x`` with
``xᵀθ̂ > τ``, some model in the ε-Rashomon set predicts the other label iff
``min_{xᵀθ = τ} L(θ) ≤ L(θ̂) + ε`` (by convexity the set meets the hyperplane iff
it contains a point on it). For linear models the minimum has a closed form;
for logistic models it is found by Newton's method on the hyperplane
(a KKT system per step) with Armijo backtracking, started from ``theta0`` if
given (must satisfy the constraint) and otherwise from the minimiser of the
quadratic model of the loss on the hyperplane.
"""
if not self._fitted or self._theta_hat is None or self._L_hat is None or self._lambda is None:
raise RuntimeError("Call fit() first.")
s = np.asarray(s, dtype=float)
if s.ndim != 1 or s.shape[0] != self._d:
raise ValueError("s must be a 1D vector of length d")
theta_hat = self._theta_hat
gap = float(c) - float(s @ theta_hat)
if gap == 0.0:
return float(self._L_hat)
if float(s @ s) == 0.0:
return np.inf # the functional is identically 0 != c: the hyperplane is empty
hinv_s = self._hinv(s)
quad = float(s @ hinv_s)
if self.estimator == "linear":
# L(θ) - L̂ = ½ (θ-θ̂)ᵀ H (θ-θ̂); the minimum on the hyperplane is ½ gap² / sᵀH⁻¹s.
return float(self._L_hat) + (0.5 * gap * gap / quad if quad > 0 else np.inf)
assert self._X is not None and self._y is not None
X, y, lam, mask, sw = self._X, self._y, float(self._lambda), self._reg_mask_or_ones(), self._sw_or_ones()
n, d = X.shape
if theta0 is not None:
theta = np.array(theta0, dtype=float)
elif quad > 0:
theta = theta_hat + hinv_s * (gap / quad) # quadratic-model minimiser on the hyperplane
else:
theta = theta_hat + s * (gap / float(s @ s)) # Euclidean projection
L_curr = self._logistic_loss(X, y, theta, lam, mask, sw)
gtol = min(self.tol, 1e-8)
K = np.zeros((d + 1, d + 1))
K[:d, d] = s
K[d, :d] = s
rhs = np.zeros(d + 1)
for _ in range(100):
p = _sigmoid(X @ theta)
g = (X.T @ (sw * (p - y))) / n + lam * mask * theta
# projected gradient (component of g along the hyperplane)
g_proj = g - s * (float(g @ s) / float(s @ s))
if float(np.linalg.norm(g_proj)) <= gtol:
break
w = sw * p * (1.0 - p)
K[:d, :d] = (X.T @ (X * w[:, None])) / n + lam * np.diag(mask) + 1e-12 * np.eye(d)
rhs[:d] = -g
rhs[d] = 0.0 # already feasible
try:
step = np.linalg.solve(K, rhs)[:d]
except np.linalg.LinAlgError:
step = -g_proj
slope = float(g @ step) # negative for a descent direction
if slope >= 0.0:
step = -g_proj
slope = float(g @ step)
t = 1.0
accepted = False
while t > 1e-10:
theta_new = theta + t * step
L_new = self._logistic_loss(X, y, theta_new, lam, mask, sw)
if L_new <= L_curr + 1e-4 * t * slope:
accepted = True
break
t *= 0.5
if not accepted:
break
theta, L_curr = theta_new, L_new
return float(L_curr)
def _hyperplane_flip_tests(self, S: Array, c: float, target: float, chunk: int = 512) -> Array:
"""Decide ``min_{sᵢᵀθ = c} L(θ) ≤ target`` for many rows at once (logistic models).
The quadratic model's minimiser on each hyperplane, ``θ̂ + gap·H⁻¹s / sᵀH⁻¹s``, is a
feasible point, so its loss is an upper bound on the minimum: one vectorised
loss evaluation settles every row for which it is already inside the set. The
remaining rows are solved exactly by :meth:`min_loss_on_hyperplane`, warm-started
from that point (usually two Newton steps).
"""
assert self._X is not None and self._y is not None and self._theta_hat is not None
assert self._lambda is not None
X, y, lam, mask, sw = self._X, self._y, float(self._lambda), self._reg_mask_or_ones(), self._sw_or_ones()
theta_hat = self._theta_hat
out = np.zeros(S.shape[0], dtype=bool)
for start in range(0, S.shape[0], chunk):
Sc = S[start:start + chunk]
gap = c - Sc @ theta_hat
U = self._hinv(Sc.T) # H^{-1} s_i, (d, m)
denom = np.sum(Sc.T * U, axis=0) # s_i^T H^{-1} s_i
Theta = theta_hat[None, :] + (U * (gap / denom)[None, :]).T
Z = X @ Theta.T
L_q = np.mean(sw[:, None] * (np.logaddexp(0.0, Z) - y[:, None] * Z), axis=0)
L_q += 0.5 * lam * np.sum(Theta * Theta * mask[None, :], axis=1)
flip = L_q <= target
for j in np.flatnonzero(~flip):
flip[j] = self.min_loss_on_hyperplane(Sc[j], c, theta0=Theta[j]) <= target
out[start:start + chunk] = flip
return out
[docs]
def can_flip(self, X: Array, tau: float = 0.0, coef_box: Optional[Array] = None) -> Array:
"""Exact per-row test: can some model in the set put row ``i`` on the other side of ``tau``?
Returns a boolean array over the rows of ``X`` (raw features; the intercept is
handled internally). Rows exactly on the threshold under θ̂ count as flippable.
Two rigorous screens avoid most optimisations: the strong-convexity bound
``|xᵀ(θ-θ̂)| ≤ ||x|| sqrt(2ε/λ)`` and, if ``coef_box`` (the exact per-coordinate
ranges from :meth:`coef_extremes`, shape (d, 2)) is given, the fact that the set
lies inside that box, so ``xᵀθ`` cannot reach ``tau`` if no point of the box does.
The rest are decided by the hyperplane minimum (closed form for linear models,
:meth:`_hyperplane_flip_tests` for logistic).
"""
if not self._fitted or self._theta_hat is None or self._epsilon_value is None or self._L_hat is None:
raise RuntimeError("Call fit() first.")
Xa = self._prepare_X(np.asarray(X, dtype=float))
scores = Xa @ self._theta_hat
eps = float(self._epsilon_value)
target = float(self._L_hat) + eps + self._membership_slack()
margin = scores - tau
out = margin == 0.0
lam = float(self._lambda) if self._lambda is not None else 0.0
penalized_all = bool(self._reg_mask is None or np.all(self._reg_mask > 0))
radius = np.sqrt(2.0 * eps / lam) if (lam > 0.0 and penalized_all) else np.inf
norms = np.linalg.norm(Xa, axis=1)
candidate = ~out & (np.abs(margin) <= radius * norms) & (norms > 0)
if coef_box is not None:
box = np.asarray(coef_box, dtype=float)
if box.shape != (self._d, 2):
raise ValueError(f"coef_box must have shape ({self._d}, 2)")
# extreme values of xᵀθ over the box: pick lo or hi per coordinate by the sign of x
box_min = np.minimum(Xa * box[:, 0], Xa * box[:, 1]).sum(axis=1)
box_max = np.maximum(Xa * box[:, 0], Xa * box[:, 1]).sum(axis=1)
reachable = np.where(margin > 0, box_min <= tau, box_max >= tau)
candidate &= reachable
todo = np.flatnonzero(candidate)
if todo.size == 0:
return out
if self.estimator == "linear":
out[todo] = np.array([self.min_loss_on_hyperplane(Xa[i], tau) <= target for i in todo])
else:
out[todo] = self._hyperplane_flip_tests(Xa[todo], tau, target)
return out
[docs]
def coef_extremes(self, indices: Optional[Array] = None) -> Array:
"""Exact per-coordinate ``[min, max]`` over the ε-Rashomon set (see :meth:`functional_range`).
Returns an array of shape ``(m, 2)``; coordinates include the intercept (index 0)
when ``fit_intercept=True``.
"""
if not self._fitted:
raise RuntimeError("Call fit() first.")
d = self._d
idx = np.arange(d) if indices is None else np.asarray(indices, dtype=int)
out = np.empty((idx.shape[0], 2), dtype=float)
for k, j in enumerate(idx):
e = np.zeros(d, dtype=float)
e[j] = 1.0
out[k] = self.functional_range(e)
return out
@staticmethod
def _logistic_loss(
X: Array, y: Array, theta: Array, lam: float, mask: Optional[Array] = None, sw: Optional[Array] = None
) -> float:
z = X @ theta
m = 1.0 if mask is None else mask
w = 1.0 if sw is None else sw
# weighted average logistic loss + (masked) L2
L = np.mean(w * (np.logaddexp(0.0, z) - y * z)) + 0.5 * lam * float(theta @ (m * theta))
return float(L)
def _sw_or_ones(self) -> Array:
return np.ones(self._n, dtype=float) if self._sw is None else self._sw
def _estimate_hessian_condition_number(self) -> Optional[float]:
if self._X is None or self._w_diag is None or self._lambda is None:
return None
# H = X^T W X / n + lam * diag(mask); eigenvalues of the (small) d x d matrix.
try:
eigs = np.linalg.eigvalsh(self._hessian_matrix())
if eigs.size == 0:
return None
eig_min, eig_max = float(eigs[0]), float(eigs[-1])
if eig_min <= 0:
return np.inf
return float(eig_max / eig_min)
except Exception:
return None
def _compute_min_signed_margin(self) -> Optional[float]:
if self._X is None or self._theta_hat is None or self._y is None:
return None
t = 2.0 * self._y - 1.0 # map {0,1} -> {-1, +1}
m = t * (self._X @ self._theta_hat)
return float(np.min(m))
def _calibrate_epsilon(self) -> Tuple[float, Optional[float]]:
if self._L_hat is None or self._n is None or self._d is None:
raise RuntimeError("Fit before calibrating epsilon")
mode = self.epsilon_mode
if mode == "absolute":
eps = float(self.epsilon)
if not (eps > 0.0) or not np.isfinite(eps):
raise ValueError("absolute epsilon must be a finite positive loss gap")
return eps, None
if mode == "percent_loss":
rho = float(self.epsilon)
if not (0.0 < rho < 1.0):
warnings.warn("percent_loss expects epsilon in (0,1); clipping", stacklevel=2)
rho = float(np.clip(rho, 1e-12, 1 - 1e-12))
return rho * float(self._L_hat), None
if mode == "LR_alpha":
alpha = float(self.epsilon)
if not _HAS_SCIPY:
warnings.warn("scipy not available; falling back to percent_loss calibration", stacklevel=2)
return 0.05 * float(self._L_hat), None
if not (0.0 < alpha < 1.0):
warnings.warn("LR_alpha expects alpha in (0,1); clipping", stacklevel=2)
alpha = float(np.clip(alpha, 1e-12, 1 - 1e-12))
# Wilks' theorem: 2n*DeltaL ~ chi^2_d. Exact when lambda=0 (unpenalized);
# approximate under weak penalization. Use chi2 path when lambda is
# small relative to the data term, or when user overrides.
lam_ratio = float(self._lambda or 0.0) * self._d / (float(self._L_hat) + 1e-12)
wilks_ok = lam_ratio < 0.1 # regularization contributes < 10% of loss
if wilks_ok or self.safety_override:
eps = 0.5 * chi2.ppf(1.0 - alpha, df=self._d) / self._n
return float(eps), alpha
if self.bootstrap_fallback:
epsb = self._bootstrap_lr_alpha(alpha)
return float(epsb), alpha
warnings.warn("Wilks preconditions violated (penalized/high-dim). Falling back to percent_loss.", stacklevel=2)
return 0.05 * float(self._L_hat), None
if mode == "LR_alpha_highdim":
raise ValueError(
"epsilon_mode='LR_alpha_highdim' has been removed: it inflated the chi-square quantile by "
"1/(1 - d/n), which is not the Sur & Candès (2019) correction it was described as. No "
"high-dimensional LR calibration is provided; use an 'absolute' or 'percent_loss' tolerance "
"(or audit(..., tolerance='cv')) when d/n is not small."
)
warnings.warn("Unknown epsilon_mode; defaulting to percent_loss 5%", stacklevel=2)
return 0.05 * float(self._L_hat), None
# --------------------------- H, CG, and norms ---------------------------
def _Hv(self, v: Array) -> Array:
if self._X is None or self._w_diag is None or self._lambda is None:
raise RuntimeError("Operators not initialized")
X = self._X
n = self._n
reg_v = self._lambda * self._reg_mask_or_ones() * v
WXv = self._w_diag * (X @ v)
return (X.T @ WXv) / n + reg_v
def _get_preconditioner_diag(self) -> Array:
"""Compute diagonal preconditioner approximation to H^{-1}.
Caches result for repeated CG solves (D17 optimization).
"""
if self._H_inv_diag is not None:
return self._H_inv_diag
if self._X is None or self._lambda is None:
raise RuntimeError("Model not fitted")
# Diagonal of H = diag(X^T W X)/n + lambda
X = self._X
n = self._n
reg_diag = self._lambda * self._reg_mask_or_ones()
if self._w_diag is None:
raise RuntimeError("Weights unavailable")
H_diag = np.sum((X ** 2) * self._w_diag[:, None], axis=0) / n + reg_diag
# Inverse diagonal for preconditioning
self._H_inv_diag = 1.0 / (H_diag + 1e-12)
return self._H_inv_diag
def _cg_solve(self, b: Array, tol: float, max_iter: int, precondition: bool = True) -> Array:
"""Conjugate gradient solver with optional diagonal preconditioning.
Optimized with caching (D17).
"""
x = np.zeros_like(b)
r = b - self._Hv(x)
# Apply preconditioner
if precondition:
M_inv_diag = self._get_preconditioner_diag()
z = M_inv_diag * r
p = z.copy()
rsold = float(r @ z)
else:
p = r.copy()
rsold = float(r @ r)
if np.sqrt(abs(rsold)) < tol:
return x
for _ in range(max_iter):
Ap = self._Hv(p)
pAp = float(p @ Ap)
if abs(pAp) < 1e-18:
break
alpha = rsold / pAp
x = x + alpha * p
r = r - alpha * Ap
if precondition:
z = M_inv_diag * r
rsnew = float(r @ z)
else:
rsnew = float(r @ r)
if np.sqrt(abs(rsnew)) < tol:
break
beta = rsnew / rsold
if precondition:
p = z + beta * p
else:
p = r + beta * p
rsold = rsnew
return x
def _whiten_direction(self, g: Array) -> Array:
"""Return L^{-T} g where H = L L^T, so that Cov(L^{-T} g) = H^{-1} for g ~ N(0, I)."""
try:
L = self._hessian_cholesky()
except RuntimeError:
return self._cg_solve(g, tol=self.tol, max_iter=self.max_iter, precondition=True)
if _HAS_SCIPY:
return np.asarray(solve_triangular(L.T, g, lower=False), dtype=float)
return np.linalg.solve(L.T, g)
def _hinv_norm(self, s: Array) -> float:
z = self._cg_solve(s, tol=self.tol, max_iter=self.max_iter, precondition=True)
val = float(np.sqrt(max(s @ z, 0.0)))
return val
def _lanczos_hinvsqrt_v(self, v: Array, m: int = 30) -> Array:
"""Approximate H^{-1/2} v via m-step Lanczos iteration.
Builds a Krylov subspace with the Hessian-vector product, then
computes f(H)v = V T^{-1/2} V^T v where T is the tridiagonal
Lanczos matrix and V the orthonormal basis.
Parameters
----------
v : array of shape (d,)
Input vector.
m : int
Number of Lanczos steps (default 30, capped at d).
Returns
-------
array of shape (d,)
Approximate H^{-1/2} v.
"""
d = self._d
m = min(m, d)
V = np.zeros((m + 1, d), dtype=float)
alphas = np.zeros(m, dtype=float)
betas = np.zeros(m, dtype=float)
norm_v = float(np.linalg.norm(v))
if norm_v < 1e-18:
return np.zeros(d, dtype=float)
V[0] = v / norm_v
for j in range(m):
w = self._Hv(V[j])
if j > 0:
w -= betas[j - 1] * V[j - 1]
alphas[j] = float(V[j] @ w)
w -= alphas[j] * V[j]
# Re-orthogonalize
for k in range(j + 1):
w -= float(V[k] @ w) * V[k]
beta_j = float(np.linalg.norm(w))
if beta_j < 1e-14:
m = j + 1
break
betas[j] = beta_j
if j + 1 < m:
V[j + 1] = w / beta_j
# Build tridiagonal matrix T
T = np.diag(alphas[:m])
for j in range(m - 1):
T[j, j + 1] = betas[j]
T[j + 1, j] = betas[j]
# Eigendecompose T
eigvals, eigvecs = np.linalg.eigh(T)
# Clip for numerical safety
eigvals = np.maximum(eigvals, 1e-12)
# T^{-1/2} = S diag(lambda^{-1/2}) S^T
f_eigvals = 1.0 / np.sqrt(eigvals)
# H^{-1/2} v ≈ ||v|| V_m S diag(f) S^T e_1
e1 = np.zeros(m)
e1[0] = 1.0
coeff = eigvecs @ (f_eigvals * (eigvecs.T @ e1))
result = norm_v * (V[:m].T @ coeff)
return result
# --------------------- Bootstrap LR_alpha fallback (B9b) ----------------
def _bootstrap_lr_alpha(self, alpha: float) -> float:
"""Parametric bootstrap calibration for LR_alpha.
Approximates the (1-α) quantile of 2n [L_b(θ̂) - L_b(θ̂_b)] over
bootstrap resamples y_b ~ Bernoulli(σ(X θ̂)) and returns ε = q/(2n).
Notes
-----
- Only implemented for logistic models.
- Uses the same λ as the fitted model.
- Deterministic given random_state.
"""
if self.estimator != "logistic":
warnings.warn("Bootstrap LR_alpha implemented for logistic only; using percent_loss fallback", stacklevel=2)
return 0.05 * float(self._L_hat) # type: ignore[arg-type]
if self._X is None or self._theta_hat is None or self._lambda is None or self._n is None:
raise RuntimeError("Model not fully initialized for bootstrap")
X = self._X
n = self._n
lam = self._lambda
theta_hat = self._theta_hat
z = X @ theta_hat
p = _sigmoid(z)
rng = np.random.default_rng(self._seed if self._seed is not None else 123456789)
reps = max(int(self.bootstrap_reps), 10)
lr_vals = np.empty(reps, dtype=float)
mask = self._reg_mask_or_ones()
sw = self._sw_or_ones()
for b in range(reps):
y_b = (rng.random(n) < p).astype(float)
theta_b, L_hat_b, _w = self._fit_logistic_l2(X, y_b, lam, mask, theta_init=theta_hat, sw=sw)
L_b_at_hat = self._logistic_loss(X, y_b, theta_hat, lam, mask, sw)
lr_b = 2.0 * n * max(L_b_at_hat - L_hat_b, 0.0)
lr_vals[b] = lr_b
# empirical quantile
q = float(np.quantile(lr_vals, 1.0 - alpha))
eps = q / (2.0 * n)
return float(eps)
# -------------------------- Sampling Diagnostics (D18) ------------------
[docs]
def compute_sample_diagnostics(
self,
samples: Array,
*,
burnin: int = 0,
compute_ess: bool = True,
compute_isotropy: bool = True,
) -> Dict[str, Any]:
"""Compute diagnostics for sampled parameters (ESS/min, chords, isotropy).
Parameters
----------
samples : array of shape (n_samples, d)
Sampled parameter vectors.
burnin : int
Number of initial samples to discard.
compute_ess : bool
Whether to compute effective sample size per minute (requires timing).
compute_isotropy : bool
Whether to compute isotropy ratio.
Returns
-------
dict with keys:
- 'n_samples': number of samples after burnin
- 'set_fidelity': fraction of samples inside Rashomon set
- 'chord_mean': mean Euclidean distance between consecutive samples
- 'chord_std': std of chord distances
- 'chord_min': minimum chord distance
- 'chord_max': maximum chord distance
- 'isotropy_ratio': max/min eigenvalue of sample covariance (if requested)
- 'ess_per_param': ESS per parameter (if autocorrelation computable)
"""
if samples.ndim != 2 or samples.shape[1] != self._d:
raise ValueError("samples must be (n_samples, d)")
if burnin > 0:
samples = samples[burnin:]
n_samples = samples.shape[0]
if n_samples < 2:
return {
"n_samples": n_samples,
"set_fidelity": None,
"chord_mean": None,
"chord_std": None,
"chord_min": None,
"chord_max": None,
"isotropy_ratio": None,
"ess_per_param": None,
}
# Set fidelity: fraction inside epsilon-Rashomon set
mask = self.contains_many(samples)
set_fidelity = float(np.mean(mask))
# Chord statistics: Euclidean distance between consecutive samples
diffs = np.diff(samples, axis=0)
chords = np.linalg.norm(diffs, axis=1)
chord_mean = float(np.mean(chords))
chord_std = float(np.std(chords))
chord_min = float(np.min(chords))
chord_max = float(np.max(chords))
# Isotropy: eigenvalue ratio of sample covariance
isotropy_ratio = None
if compute_isotropy and n_samples >= self._d + 1:
try:
cov = np.cov(samples, rowvar=False)
eigvals = np.linalg.eigvalsh(cov)
eigvals = eigvals[eigvals > 1e-12] # filter numerical zeros
if len(eigvals) >= 2:
isotropy_ratio = float(eigvals[-1] / eigvals[0])
except Exception:
isotropy_ratio = None
# ESS per parameter (Geyer's initial positive sequence estimator)
ess_per_param = None
if compute_ess and n_samples >= 10:
try:
ess_per_param = np.array([_ess_geyer(samples[:, j]) for j in range(self._d)], dtype=float)
except Exception:
ess_per_param = None
return {
"n_samples": n_samples,
"set_fidelity": set_fidelity,
"chord_mean": chord_mean,
"chord_std": chord_std,
"chord_min": chord_min,
"chord_max": chord_max,
"isotropy_ratio": isotropy_ratio,
"ess_per_param": ess_per_param,
}
# ----------------------------- Coefficient stability ---------------------
[docs]
def variable_importance_cloud(
self,
*,
n_samples: int = 200,
sampler: Optional[str] = None,
feature_names: Optional[list] = None,
burnin: int = 100,
thin: int = 2,
random_state: Optional[int] = None,
) -> Dict[str, Any]:
"""Coefficient distribution across the Rashomon set.
Samples parameter vectors from the Rashomon set and computes the
distribution of each coefficient, showing which features have stable
vs. unstable weightings across near-optimal models.
Inspired by the Variable Importance Cloud concept of Dong & Rudin
(2020, Nature Machine Intelligence), adapted to the GLM setting
where raw coefficients serve as the importance measure. Note that
Dong & Rudin's original VIC uses SHAP-based importance over tree
models; this method uses raw coefficients, which is the natural
analog for linear models but only an approximation of importance
for logistic regression (coefficients are in log-odds space).
Parameters
----------
n_samples : int
Number of parameter samples to draw.
sampler : Optional[str]
Sampler to use ("ellipsoid" or "hitandrun"). Defaults to self.sampler.
feature_names : Optional[list]
Names of the features (length d_original; "(intercept)" is prepended when
fit_intercept=True) or of all coordinates (length d). If None, uses indices.
burnin : int
Burn-in for Hit-and-Run sampler (ignored for ellipsoid).
thin : int
Thinning for Hit-and-Run sampler (ignored for ellipsoid).
random_state : Optional[int]
Random seed for sampling.
Returns
-------
dict with keys:
- 'samples': array of shape (n_samples, d) - parameter samples
- 'mean': array of shape (d,) - mean coefficients
- 'std': array of shape (d,) - std of coefficients
- 'quantiles': dict with keys (0.05, 0.25, 0.5, 0.75, 0.95)
- 'intervals': array of shape (d, 2) - 90% intervals
- 'feature_names': list of feature names
"""
if not self._fitted:
raise RuntimeError("Call fit() first.")
# Determine sampler
backend = sampler if sampler is not None else self.sampler
# Generate samples
seed = self._seed if random_state is None else int(random_state)
if backend.lower() == "ellipsoid":
samples = self.sample_ellipsoid(n_samples=n_samples, random_state=seed)
elif backend.lower() == "hitandrun":
samples = self.sample_hitandrun(
n_samples=n_samples,
burnin=burnin,
thin=thin,
random_state=seed,
compute_diagnostics=False,
)
else:
raise ValueError(f"Unknown sampler: {backend}")
# Compute statistics
mean = np.mean(samples, axis=0)
std = np.std(samples, axis=0)
# Quantiles
quantiles = {}
for q in [0.05, 0.25, 0.5, 0.75, 0.95]:
quantiles[q] = np.quantile(samples, q, axis=0)
# 90% intervals
intervals = np.stack([quantiles[0.05], quantiles[0.95]], axis=1)
names = self._coordinate_names(feature_names)
return {
"samples": samples,
"mean": mean,
"std": std,
"quantiles": quantiles,
"intervals": intervals,
"feature_names": names,
}
[docs]
def plot_vic(
self,
vic_result: Optional[Dict[str, Any]] = None,
*,
n_samples: int = 200,
feature_names: Optional[list] = None,
figsize: Optional[tuple] = None,
show_theta_hat: bool = True,
**kwargs: Any,
) -> Any:
"""Plot coefficient distributions across the Rashomon set.
Parameters
----------
vic_result : Optional[dict]
Pre-computed VIC result. If None, computes internally.
n_samples : int
Number of samples if computing VIC internally.
feature_names : Optional[list]
Feature names for axis labels.
figsize : Optional[tuple]
Figure size (width, height).
show_theta_hat : bool
If True, show optimal theta_hat as reference.
**kwargs
Additional arguments for variable_importance_cloud().
Returns
-------
matplotlib Figure and Axes objects.
"""
try:
from .plotting import plot_vic
except ImportError as exc:
raise ImportError("matplotlib is required for plotting. Install via: pip install matplotlib") from exc
# Compute VIC if not provided
if vic_result is None:
vic_result = self.variable_importance_cloud(
n_samples=n_samples,
feature_names=feature_names,
**kwargs,
)
return plot_vic(
vic_result,
theta_hat=self._theta_hat if show_theta_hat else None,
figsize=figsize
)
[docs]
def plot_ambiguity(
self,
X: Array,
threshold_mode: str = "fixed",
threshold_value: float | None = None,
y: Array | None = None,
figsize: Optional[tuple] = None,
**kwargs: Any,
) -> Any:
"""Plot predictive ambiguity distribution.
Parameters
----------
X : Array
Data to evaluate.
threshold_mode : str
Threshold selection mode.
threshold_value : float
Value for fixed threshold.
y : Array
Labels (optional).
figsize : tuple
Figure size.
Returns
-------
fig, ax
"""
try:
from .plotting import plot_ambiguity
except ImportError as exc:
raise ImportError("matplotlib is required for plotting") from exc
# Compute margins
margins = self.decision_function(X)
# Compute threshold and ambiguous set
amb_result = self.ambiguity(
X, threshold_mode, threshold_value, y, **kwargs
)
return plot_ambiguity(
margins,
threshold=amb_result["threshold"],
ambiguous_indices=amb_result["ambiguous_indices"],
figsize=figsize
)
[docs]
def plot_discrepancy(
self,
X: Array,
samples: Array | None = None,
n_samples: int = 50,
n_pairs: int = 100,
threshold_mode: str = "fixed",
threshold_value: float | None = None,
y: Array | None = None,
figsize: Optional[tuple] = None,
**kwargs: Any,
) -> Any:
"""Plot pairwise discrepancy heatmap.
Parameters
----------
X : Array
Data matrix.
samples : Array, optional
Pre-computed samples.
n_samples : int
Number of samples to draw.
n_pairs : int
Number of pairs (not used for heatmap, used for metric).
threshold_mode : str
Threshold selection mode.
y : Array
Labels.
figsize : tuple
Figure size.
Returns
-------
fig, ax
"""
try:
from .plotting import plot_discrepancy
except ImportError as exc:
raise ImportError("matplotlib is required for plotting") from exc
if not self._fitted:
raise RuntimeError("Call fit() first")
X = self._prepare_X(np.asarray(X))
# 1. Get samples
if samples is None:
samples = self.sample(n_samples)
else:
n_samples = len(samples)
# 2. Compute predictions
tau = self.compute_threshold(y if y is not None else np.zeros(1), threshold_mode, threshold_value, **kwargs)
margins = X @ samples.T
preds = (margins >= tau).astype(int)
# 3. Compute pairwise discrepancy matrix
disc_matrix = np.zeros((n_samples, n_samples))
for i in range(n_samples):
for j in range(i + 1, n_samples):
d = float(np.mean(preds[:, i] != preds[:, j]))
disc_matrix[i, j] = d
disc_matrix[j, i] = d
return plot_discrepancy(disc_matrix, figsize=figsize)
# ------------------------------ Deprecated -------------------------------
[docs]
def variable_importance(self, mode: str = "VIC") -> Any:
"""Deprecated: use variable_importance_cloud() instead."""
warnings.warn(
"variable_importance() is deprecated; use variable_importance_cloud()",
DeprecationWarning,
stacklevel=2,
)
if mode.upper() == "VIC":
return self.variable_importance_cloud()
raise NotImplementedError(f"Mode '{mode}' not implemented")
[docs]
def model_class_reliance(
self,
X: Array,
y: Array,
*,
n_permutations: int = 16,
n_samples: int = 100,
perm_mode: str = "iid",
sampler: Optional[str] = None,
burnin: int = 100,
thin: int = 2,
check_collinearity: bool = True,
random_state: Optional[int] = None,
metric: str = "score",
) -> Dict[str, Any]:
"""Permutation importance across sampled models (model class reliance).
Computes feature importance by measuring performance degradation under
permutation for each of ``n_samples`` models drawn from the Rashomon set.
``mcr_min`` / ``mcr_max`` are the extremes over those *sampled* models. They
are an inner approximation of the model class reliance interval of Fisher,
Rudin & Dominici (2019): the true range over the whole set can only be wider,
and the approximation tightens as ``n_samples`` grows.
Parameters
----------
X : array of shape (n, d)
Feature matrix.
y : array of shape (n,)
Target vector.
n_permutations : int
Number of permutation replicates per feature.
n_samples : int
Number of parameter samples from Rashomon set.
perm_mode : str
Permutation strategy:
- "iid": independent permutation (baseline)
- "residual": permute partial residuals (correlation-aware)
- "conditional": permute within bins of correlated features
metric : {"score", "loss_ratio"}
- "score" (default): importance is the drop in accuracy (logistic) or
R² (linear) under permutation.
- "loss_ratio": importance is the Fisher–Rudin–Dominici reliance
``loss(permuted) / loss(original)`` with log-loss (logistic) or MSE
(linear); 1 means the feature is not used.
sampler : Optional[str]
Sampler to use ("ellipsoid" or "hitandrun"). Defaults to
self.sampler. Using "hitandrun" ensures all samples are
within the true Rashomon set.
burnin : int
Burn-in for Hit-and-Run sampler (ignored for ellipsoid).
thin : int
Thinning for Hit-and-Run sampler (ignored for ellipsoid).
check_collinearity : bool
If True, warn when features are highly correlated.
random_state : Optional[int]
Random seed.
Returns
-------
dict with keys:
- 'feature_importance': array (d,) - mean importance across samples
- 'importance_std': array (d,) - std across samples
- 'mcr_min': array (d,) - min importance across the sampled models
- 'mcr_max': array (d,) - max importance across the sampled models
- 'importance_matrix': array (n_samples, d) - per-sample importances
- 'base_score': float - baseline score (or loss) at theta_hat
- 'metric': str - the metric used
- 'collinearity_warning': Optional[list] - correlated feature pairs
Coordinates follow the internal layout: with ``fit_intercept=True`` the
intercept is column 0 and is never permuted (importance 0 / ratio 1).
References
----------
Fisher, Rudin, Dominici (2019). "All Models are Wrong, but Many
are Useful."
"""
if not self._fitted:
raise RuntimeError("Call fit() first.")
X = self._prepare_X(np.asarray(X))
y = np.asarray(y)
if X.ndim != 2 or X.shape[1] != self._d:
raise ValueError("X must be 2D with d features")
seed = self._seed if random_state is None else int(random_state)
rng = np.random.default_rng(seed)
# Check for collinearity
collinear_pairs = []
if check_collinearity and X.shape[0] >= self._d:
try:
corr_matrix = np.corrcoef(X, rowvar=False)
for i in range(self._d):
for j in range(i + 1, self._d):
if abs(corr_matrix[i, j]) > 0.85:
collinear_pairs.append((i, j, corr_matrix[i, j]))
if collinear_pairs:
warnings.warn(
f"High collinearity detected: {len(collinear_pairs)} pairs. "
"Consider using perm_mode='residual' or 'conditional'.",
stacklevel=2,
)
except Exception:
pass
# Sample parameters from Rashomon set using configured sampler
backend = sampler if sampler is not None else self.sampler
if backend.lower() == "ellipsoid":
samples = self.sample_ellipsoid(n_samples=n_samples, random_state=seed)
elif backend.lower() == "hitandrun":
samples = self.sample_hitandrun(
n_samples=n_samples,
burnin=burnin,
thin=thin,
random_state=seed,
compute_diagnostics=False,
)
else:
raise ValueError(f"Unknown sampler: {backend}")
if metric not in ("score", "loss_ratio"):
raise ValueError("metric must be 'score' or 'loss_ratio'")
# Pre-compute ss_tot for linear models (used across all samples)
y_mean = float(np.mean(y))
ss_tot = float(np.sum((y - y_mean) ** 2))
def evaluate(Xm: Array, theta: Array) -> float:
"""Score (accuracy / R²) or loss (log-loss / MSE) of theta on Xm."""
scores = Xm @ theta
if metric == "loss_ratio":
if self.estimator == "logistic":
return float(np.mean(np.logaddexp(0.0, scores) - y * scores))
return float(np.mean((y - scores) ** 2))
if self.estimator == "logistic":
return float(np.mean(((scores > 0.0).astype(int) == y.astype(int)).astype(float)))
ss_res = float(np.sum((y - scores) ** 2))
return 1.0 - ss_res / ss_tot if ss_tot > 0 else 1.0
def importance(base: float, permuted: float) -> float:
if metric == "loss_ratio":
return permuted / base if base > 0 else 1.0
return base - permuted
# Compute importance for each sampled parameter
first_feature = 1 if self.fit_intercept else 0 # never permute the intercept column
importance_matrix = np.zeros((n_samples, self._d), dtype=float)
if metric == "loss_ratio" and self.fit_intercept:
importance_matrix[:, 0] = 1.0
for s_idx in range(n_samples):
theta_s = samples[s_idx]
base = evaluate(X, theta_s)
# Permutation importance for each feature
for j in range(first_feature, self._d):
perm_scores = np.zeros(n_permutations, dtype=float)
for p in range(n_permutations):
Xp = X.copy()
if perm_mode == "iid":
# Standard permutation
rng.shuffle(Xp[:, j])
elif perm_mode == "residual":
# Partial residual permutation (correlation-aware)
# Regress X[:,j] on other features to get partial residual
X_other = np.delete(X, j, axis=1)
# Fast least-squares via normal equations
XtX = X_other.T @ X_other
Xty = X_other.T @ X[:, j]
try:
beta = np.linalg.solve(
XtX + 1e-8 * np.eye(X_other.shape[1]), Xty
)
predicted_j = X_other @ beta
except np.linalg.LinAlgError:
predicted_j = np.zeros(X.shape[0])
residual_j = X[:, j] - predicted_j
residual_j_perm = residual_j.copy()
rng.shuffle(residual_j_perm)
Xp[:, j] = predicted_j + residual_j_perm
elif perm_mode == "conditional":
# Conditional permutation (simplified: bin-based)
# Bin samples by correlated features and permute within bins
n_bins = max(3, int(np.sqrt(X.shape[0])))
# Use mean of other features for binning
other_mean = np.mean(np.delete(X, j, axis=1), axis=1)
bins = np.digitize(other_mean, np.linspace(other_mean.min(), other_mean.max(), n_bins))
for b in range(1, n_bins + 1):
mask = bins == b
if np.sum(mask) > 1:
Xp[mask, j] = rng.permutation(Xp[mask, j])
else:
raise ValueError(f"Unknown perm_mode: {perm_mode}")
perm_scores[p] = evaluate(Xp, theta_s)
importance_matrix[s_idx, j] = importance(base, float(np.mean(perm_scores)))
# Aggregate: mean/std (sampling estimate) + min/max over the sampled models
mean_importance = np.mean(importance_matrix, axis=0)
std_importance = np.std(importance_matrix, axis=0)
mcr_min = np.min(importance_matrix, axis=0)
mcr_max = np.max(importance_matrix, axis=0)
assert self._theta_hat is not None
base_score = evaluate(X, self._theta_hat)
return {
"feature_importance": mean_importance,
"importance_std": std_importance,
"mcr_min": mcr_min,
"mcr_max": mcr_max,
"importance_matrix": importance_matrix,
"base_score": base_score,
"metric": metric,
"collinearity_warning": collinear_pairs if collinear_pairs else None,
}
[docs]
def mcr_analytic(
self,
X: Array,
y: Array,
*,
n_permutations: int = 20,
score_fn: str = "loss",
random_state: Optional[int] = None,
) -> Dict[str, Any]:
"""Analytic MCR bounds via first-order relaxation of permutation importance.
Computes the gradient of permutation importance I_j(theta) at theta_hat,
then uses the hacking interval formula for analytic MCR bounds:
MCR_j^{min/max} = I_j(theta_hat) -/+ sqrt(2*eps) * ||grad_I_j||_{H^{-1}}
Two scoring functions are available:
- ``"loss"``: importance = increase in log-loss (logistic) or MSE (linear)
when feature j is permuted. This is the natural choice since the
Rashomon set is defined over the loss function.
- ``"probability"``: (logistic only) importance = mean absolute change in
predicted probability sigma(X theta) when feature j is permuted. This
is smooth (unlike accuracy) and more interpretable to practitioners
who think in terms of probability shifts.
Both are smooth in theta, giving well-defined analytic gradients.
.. note::
These are linearized estimates, not bounds: the importance is not a
linear function of theta, so the true extremes over the set can lie on
either side of them. They are typically narrower than the sampled
extremes from :meth:`model_class_reliance`, which are themselves inner
bounds (the true extremes are at least as far out). Neither method
computes the exact MCR; nothing in this package does.
Parameters
----------
X : array (n, d)
Feature matrix.
y : array (n,)
Target vector.
n_permutations : int
Number of permutation replicates to estimate I_j and grad_I_j.
score_fn : {"loss", "probability"}
Scoring function for importance. "loss" uses log-loss/MSE increase;
"probability" uses mean absolute change in predicted probability
(logistic only).
random_state : Optional[int]
Random seed.
Returns
-------
dict with:
- 'mcr_min_analytic': array (d,) - lower bounds
- 'mcr_max_analytic': array (d,) - upper bounds
- 'importance_at_hat': array (d,) - importance at theta_hat
- 'grad_norms': array (d,) - ||grad_I_j||_{H^{-1}} per feature
- 'score_fn': str - which scoring function was used
"""
if not self._fitted or self._theta_hat is None or self._epsilon_value is None:
raise RuntimeError("Call fit() first.")
X = self._prepare_X(np.asarray(X, dtype=float))
y = np.asarray(y, dtype=float)
n, d = X.shape
if score_fn == "probability" and self.estimator != "logistic":
raise ValueError("score_fn='probability' is only available for logistic regression")
seed = self._seed if random_state is None else int(random_state)
rng = np.random.default_rng(seed)
theta_hat = self._theta_hat
eps = self._epsilon_value
importance_at_hat = np.zeros(d, dtype=float)
grad_norms = np.zeros(d, dtype=float)
z_base = X @ theta_hat
if score_fn == "loss":
# Loss-based importance: L_perm - L
if self.estimator == "logistic":
base_score = float(np.mean(np.logaddexp(0.0, z_base) - y * z_base))
p_base = _sigmoid(z_base)
grad_base = (X.T @ (p_base - y)) / n
else:
resid_base = y - z_base
base_score = float(0.5 * np.mean(resid_base ** 2))
grad_base = -(X.T @ resid_base) / n
for j in range(d):
imp_sum = 0.0
grad_sum = np.zeros(d, dtype=float)
for _p in range(n_permutations):
Xp = X.copy()
rng.shuffle(Xp[:, j])
z_perm = Xp @ theta_hat
if self.estimator == "logistic":
perm_score = float(np.mean(np.logaddexp(0.0, z_perm) - y * z_perm))
p_perm = _sigmoid(z_perm)
grad_perm = (Xp.T @ (p_perm - y)) / n
else:
resid_perm = y - z_perm
perm_score = float(0.5 * np.mean(resid_perm ** 2))
grad_perm = -(Xp.T @ resid_perm) / n
imp_sum += (perm_score - base_score)
grad_sum += (grad_perm - grad_base)
importance_at_hat[j] = imp_sum / n_permutations
grad_norms[j] = self._hinv_norm(grad_sum / n_permutations)
elif score_fn == "probability":
# Probability-based importance: mean |sigma(X theta) - sigma(X_perm theta)|
p_base = _sigmoid(z_base)
# Gradient of sigma(z) w.r.t. theta: sigma'(z) * x = p(1-p) * x
w_base = p_base * (1.0 - p_base) # shape (n,)
for j in range(d):
imp_sum = 0.0
grad_sum = np.zeros(d, dtype=float)
for _p in range(n_permutations):
Xp = X.copy()
rng.shuffle(Xp[:, j])
z_perm = Xp @ theta_hat
p_perm = _sigmoid(z_perm)
diff = p_perm - p_base # signed difference
abs_diff = np.abs(diff)
imp_sum += float(np.mean(abs_diff))
# Gradient of mean|sigma(Xp theta) - sigma(X theta)| w.r.t. theta
# d/dtheta |f| = sign(f) * f' where f = sigma(Xp theta) - sigma(X theta)
# f' = sigma'(Xp theta) * Xp - sigma'(X theta) * X
sign_diff = np.sign(diff)
w_perm = p_perm * (1.0 - p_perm)
grad_perm = (Xp.T @ (sign_diff * w_perm) - X.T @ (sign_diff * w_base)) / n
grad_sum += grad_perm
importance_at_hat[j] = imp_sum / n_permutations
grad_norms[j] = self._hinv_norm(grad_sum / n_permutations)
else:
raise ValueError(f"Unknown score_fn: {score_fn}. Use 'loss' or 'probability'.")
delta = np.sqrt(2.0 * eps) * grad_norms
mcr_min = importance_at_hat - delta
mcr_max = importance_at_hat + delta
return {
"mcr_min_analytic": mcr_min,
"mcr_max_analytic": mcr_max,
"importance_at_hat": importance_at_hat,
"grad_norms": grad_norms,
"score_fn": score_fn,
}
[docs]
def shapley_vic(
self,
X: Array,
*,
n_samples: int = 200,
sampler: Optional[str] = None,
feature_names: Optional[list] = None,
burnin: int = 100,
thin: int = 2,
random_state: Optional[int] = None,
) -> Dict[str, Any]:
"""Shapley-VIC: distribution of Shapley values across the Rashomon set.
For each sampled theta, computes marginal Shapley values for each
feature using the linear SHAP formula: phi_j(x) = theta_j * (x_j - mean_j).
Aggregated over all instances to get per-feature Shapley importance.
Parameters
----------
X : array (n, d)
Data matrix (used to compute E[x_j] and aggregate Shapley values).
n_samples : int
Number of models to sample from the Rashomon set.
sampler : Optional[str]
Sampler backend ("ellipsoid" or "hitandrun").
feature_names : Optional[list]
Names of the features, or of all coordinates including the intercept.
burnin, thin : int
Hit-and-Run parameters.
random_state : Optional[int]
Seed.
Returns
-------
dict with:
- 'shapley_samples': (n_samples, d) - mean absolute Shapley value per feature per model
- 'shapley_mean': (d,) - mean across models
- 'shapley_std': (d,) - std across models
- 'shapley_min': (d,) - min across models
- 'shapley_max': (d,) - max across models
- 'feature_names': list
"""
if not self._fitted:
raise RuntimeError("Call fit() first.")
X = self._prepare_X(np.asarray(X, dtype=float))
if self.estimator == "logistic":
warnings.warn(
"shapley_vic uses the linear SHAP formula phi_j = theta_j * (x_j - E[x_j]), "
"which is exact for linear regression but only an approximation in log-odds "
"space for logistic regression. Interpret with caution.",
stacklevel=2,
)
# Sample from Rashomon set
backend = sampler if sampler is not None else self.sampler
seed = self._seed if random_state is None else int(random_state)
if backend.lower() == "ellipsoid":
samples = self.sample_ellipsoid(n_samples=n_samples, random_state=seed)
elif backend.lower() == "hitandrun":
samples = self.sample_hitandrun(
n_samples=n_samples, burnin=burnin, thin=thin,
random_state=seed, compute_diagnostics=False,
)
else:
raise ValueError(f"Unknown sampler: {backend}")
# For linear models: Shapley value for feature j = theta_j * (x_j - E[x_j])
# Mean |Shapley| importance per feature = |theta_j| * std(x_j)
x_mean = np.mean(X, axis=0)
x_centered = X - x_mean
# For each sampled theta, compute mean absolute Shapley value per feature
shapley_matrix = np.zeros((n_samples, self._d), dtype=float)
for s in range(n_samples):
theta_s = samples[s]
# Shapley values for all instances: phi[i,j] = theta_j * (x[i,j] - x_mean[j])
# Mean absolute Shapley per feature: mean_i |phi[i,j]|
shapley_matrix[s] = np.mean(np.abs(theta_s[None, :] * x_centered), axis=0)
names = self._coordinate_names(feature_names)
return {
"shapley_samples": shapley_matrix,
"shapley_mean": np.mean(shapley_matrix, axis=0),
"shapley_std": np.std(shapley_matrix, axis=0),
"shapley_min": np.min(shapley_matrix, axis=0),
"shapley_max": np.max(shapley_matrix, axis=0),
"feature_names": list(names),
}
[docs]
def compute_threshold(
self,
y: Array,
mode: str = "fixed",
value: float | None = None,
**kwargs: Any,
) -> float:
"""Compute decision threshold for binary classification.
Parameters
----------
y : Array
Training labels (needed for prevalence/base-rate).
mode : str, default="fixed"
Threshold selection mode:
- "fixed": use provided value (default 0.5 for logit 0)
- "match_prevalence": margin quantile matching the prevalence (X_val margins if given)
- "match_fpr": threshold for target false positive rate (requires fpr= kwarg)
- "youden": maximize Youden's J statistic (requires X_val, y_val kwargs)
value : float, optional
Value for "fixed" mode. If None, uses 0.5 (logit 0).
Returns
-------
threshold : float
Decision threshold in margin space (x^T theta).
Examples
--------
>>> rs.compute_threshold(y, mode="fixed", value=0.5)
0.0
>>> rs.compute_threshold(y, mode="match_prevalence")
-0.123
"""
if self.estimator != "logistic":
raise ValueError("Thresholds only applicable to logistic regression")
if not self._fitted or self._theta_hat is None:
raise RuntimeError("Call fit() first")
if mode == "fixed":
if value is None:
value = 0.5 # logit(0.5) = 0
# Convert probability threshold to margin (logit)
if value <= 0.0 or value >= 1.0:
raise ValueError("Fixed threshold must be in (0, 1)")
return float(np.log(value / (1.0 - value)))
elif mode == "match_prevalence":
# Threshold at which the fraction of positive predictions equals the
# empirical prevalence: the (1 - prevalence) quantile of the margins.
# (Earlier versions returned logit(prevalence), which does not do this.)
prevalence = float(np.mean(y))
if prevalence <= 0.0 or prevalence >= 1.0:
warnings.warn(
f"Prevalence {prevalence:.3f} at boundary; using fixed 0.5",
stacklevel=2,
)
return 0.0
X_val = kwargs.get("X_val")
if X_val is not None:
margins = self.decision_function(X_val)
else:
if self._X is None:
raise RuntimeError("Call fit() first")
margins = self._X @ self._theta_hat
return float(np.quantile(margins, 1.0 - prevalence))
elif mode == "match_fpr":
# Requires validation data to estimate threshold for target FPR
fpr_target = kwargs.get("fpr", 0.05)
X_val = kwargs.get("X_val")
y_val = kwargs.get("y_val")
if X_val is None or y_val is None:
raise ValueError("match_fpr mode requires X_val and y_val kwargs")
# Use theta_hat to find threshold achieving target FPR
margins = self.decision_function(X_val)
negatives = y_val == 0
if np.sum(negatives) == 0:
warnings.warn("No negative examples; using fixed threshold", stacklevel=2)
return 0.0
# Sort margins of negatives and pick threshold
neg_margins = np.sort(margins[negatives])
idx = int((1.0 - fpr_target) * len(neg_margins))
idx = max(0, min(idx, len(neg_margins) - 1))
return float(neg_margins[idx])
elif mode == "youden":
# Maximize Youden's J = sensitivity + specificity - 1
X_val = kwargs.get("X_val")
y_val = kwargs.get("y_val")
if X_val is None or y_val is None:
raise ValueError("youden mode requires X_val and y_val kwargs")
margins = self.decision_function(X_val)
# Grid search over possible thresholds
thresholds = np.percentile(margins, np.linspace(1, 99, 99))
best_j, best_tau = -np.inf, 0.0
for tau_val in np.atleast_1d(thresholds):
preds = margins >= tau_val
tp: int = int(np.sum((preds == 1) & (y_val == 1)))
tn: int = int(np.sum((preds == 0) & (y_val == 0)))
fp: int = int(np.sum((preds == 1) & (y_val == 0)))
fn: int = int(np.sum((preds == 0) & (y_val == 1)))
sens = tp / (tp + fn) if (tp + fn) > 0 else 0.0
spec = tn / (tn + fp) if (tn + fp) > 0 else 0.0
j = sens + spec - 1.0
if j > best_j:
best_j = j
best_tau = float(tau_val)
return best_tau
else:
raise ValueError(f"Unknown threshold mode: {mode}")
[docs]
def ambiguity(
self,
X: Array,
threshold_mode: str = "fixed",
threshold_value: float | None = None,
y: Array | None = None,
**kwargs: Any,
) -> dict[str, Any]:
"""Compute ambiguity: fraction of instances with label disagreement across Rashomon set.
For binary classification, an instance is ambiguous if its margin interval
[m_min, m_max] straddles the decision threshold τ. This indicates that some
models in the Rashomon set would classify it as 0, and others as 1.
Margin interval: m_i^{min/max} = x_i^T θ_hat ± sqrt(2ε) ||x_i||_{H^{-1}}
Parameters
----------
X : Array, shape (n, d)
Data matrix.
threshold_mode : str, default="fixed"
How to compute decision threshold: "fixed", "match_prevalence", etc.
threshold_value : float, optional
Value for fixed mode (default 0.5 = logit 0).
y : Array, optional
Labels (required for some threshold modes).
**kwargs
Additional arguments for threshold computation.
Returns
-------
result : dict
- "ambiguity_rate": fraction of ambiguous instances
- "n_ambiguous": count of ambiguous instances
- "threshold": decision threshold used (in margin space)
- "ambiguous_indices": indices of ambiguous instances
References
----------
Marx, Calmon, Ustun (2020). "Predictive Multiplicity in Classification."
ICML 2020.
Examples
--------
>>> amb = rs.ambiguity(X_test, threshold_mode="fixed", threshold_value=0.5)
>>> print(f"Ambiguity rate: {amb['ambiguity_rate']:.2%}")
"""
if not self._fitted or self._theta_hat is None or self._epsilon_value is None:
raise RuntimeError("Call fit() first")
X = self._prepare_X(X)
n = X.shape[0]
# Compute threshold
if y is None and threshold_mode != "fixed":
raise ValueError(f"Threshold mode '{threshold_mode}' requires y")
y_for_threshold = y if y is not None else np.zeros(1)
tau = self.compute_threshold(y_for_threshold, threshold_mode, threshold_value, **kwargs)
# Compute margin intervals for each instance
ambiguous = []
for i in range(n):
interval = self.hacking_interval(X[i])
m_min, m_max = interval["min"], interval["max"]
# Instance is ambiguous if interval straddles threshold
if m_min <= tau <= m_max:
ambiguous.append(i)
n_ambiguous = len(ambiguous)
ambiguity_rate = n_ambiguous / n if n > 0 else 0.0
return {
"ambiguity_rate": ambiguity_rate,
"n_ambiguous": n_ambiguous,
"threshold": tau,
"ambiguous_indices": np.array(ambiguous, dtype=int),
}
[docs]
def discrepancy(
self,
X: Array,
samples: Array | None = None,
n_samples: int = 100,
n_pairs: int = 50,
threshold_mode: str = "fixed",
threshold_value: float | None = None,
y: Array | None = None,
random_state: int | None = None,
**kwargs: Any,
) -> dict[str, Any]:
"""Estimates of the discrepancy: the largest disagreement rate between two models in the set.
The exact discrepancy is not computed. Two estimates are returned: the fraction of
rows whose Hessian-ellipsoid margin interval straddles the threshold, which
estimates an upper bound (not rigorously, since the ellipsoid is an approximation
of the set), and the disagreement rates of random pairs of sampled models, whose
maximum is an inner bound. A rigorous upper bound is the exact flip rate from
:func:`rashomon.audit`: two models can disagree on a row only if at least one of
them disagrees with the fitted model there.
Parameters
----------
X : Array, shape (n, d)
Data matrix.
samples : Array, optional
Pre-computed parameter samples, shape (n_samples, d).
If None, will sample using default method.
n_samples : int, default=100
Number of samples to draw if samples not provided.
n_pairs : int, default=50
Number of random pairs to evaluate for empirical estimate.
threshold_mode : str, default="fixed"
Threshold selection mode.
threshold_value : float, optional
Value for fixed threshold mode.
y : Array, optional
Labels (required for some threshold modes).
random_state : int, optional
Random seed.
**kwargs
Additional arguments for threshold computation.
Returns
-------
result : dict
- "discrepancy_bound": fraction of rows whose ellipsoid margin interval straddles
the threshold (estimate of an upper bound; not rigorous)
- "discrepancy_extremal_pair": disagreement between the two ellipsoid points along
the mean straddling direction (a heuristic, not the extremal pair)
- "max_pair_disagreement": largest disagreement among the sampled pairs (inner bound)
- "mean_pair_disagreement": average disagreement across the sampled pairs
- "discrepancy_empirical": the same average, kept for compatibility; it is not an
estimate of the maximum
- "threshold": decision threshold used
Examples
--------
>>> disc = rs.discrepancy(X_test, n_samples=200, n_pairs=100)
>>> print(f"Discrepancy bound: {disc['discrepancy_bound']:.2%}")
>>> print(f"Empirical estimate: {disc['discrepancy_empirical']:.2%}")
"""
if not self._fitted or self._theta_hat is None or self._epsilon_value is None:
raise RuntimeError("Call fit() first")
X = self._prepare_X(X)
n = X.shape[0]
rng = np.random.default_rng(random_state)
# Compute threshold
if y is None and threshold_mode != "fixed":
raise ValueError(f"Threshold mode '{threshold_mode}' requires y")
y_for_threshold = y if y is not None else np.zeros(1)
tau = self.compute_threshold(y_for_threshold, threshold_mode, threshold_value, **kwargs)
# Upper bound: count instances with margin interval straddling threshold
n_straddle = 0
straddle_indices = []
for i in range(n):
interval = self.hacking_interval(X[i])
m_min, m_max = interval["min"], interval["max"]
if m_min <= tau <= m_max:
n_straddle += 1
straddle_indices.append(i)
discrepancy_bound = n_straddle / n if n > 0 else 0.0
# Tighter bound via extremal pair: find the two models in the
# ellipsoidal Rashomon set that maximize disagreement. For each
# straddling instance i, the margin x_i^T theta must cross tau.
# The extremal pair pushes straddling margins in opposite directions.
# Compute via the principal direction of disagreement.
extremal_disagreement = None
if straddle_indices and self._epsilon_value is not None:
X_straddle = X[straddle_indices]
# Direction that maximizes margin spread: largest eigenvector of
# X_straddle^T X_straddle projected onto the Rashomon ellipsoid
if len(straddle_indices) >= 2:
# Find direction v that maximizes sum of |x_i^T v| for straddling instances
# within the ellipsoid. Approximation: use the principal component of X_straddle
# projected through H^{-1}.
mean_s = np.mean(X_straddle, axis=0)
hinv_mean = self._cg_solve(mean_s, tol=self.tol, max_iter=self.max_iter, precondition=True)
scale = float(np.sqrt(2.0 * self._epsilon_value))
# Extremal models: theta_hat +/- scale * hinv_mean / ||hinv_mean||_H
hinv_norm = float(np.sqrt(max(mean_s @ hinv_mean, 1e-18)))
if hinv_norm > 1e-12:
delta = scale * hinv_mean / hinv_norm
theta_plus = self._theta_hat + delta
theta_minus = self._theta_hat - delta
preds_plus = (X @ theta_plus >= tau).astype(int)
preds_minus = (X @ theta_minus >= tau).astype(int)
extremal_disagreement = float(np.mean(preds_plus != preds_minus))
# Empirical estimate: sample pairs and compute disagreement
if samples is None:
samples = self.sample(n_samples, random_state=random_state)
if len(samples) < 2:
warnings.warn("Need at least 2 samples for empirical discrepancy", stacklevel=2)
return {
"discrepancy_bound": discrepancy_bound,
"discrepancy_empirical": None,
"max_pair_disagreement": None,
"mean_pair_disagreement": None,
"threshold": tau,
}
# Compute predictions for all samples
margins = X @ samples.T # shape (n, n_samples)
preds = (margins >= tau).astype(int) # shape (n, n_samples)
# Sample pairs and compute disagreement rates
disagreements = []
for _ in range(n_pairs):
i, j = rng.choice(len(samples), size=2, replace=False)
disagreement_rate = float(np.mean(preds[:, i] != preds[:, j]))
disagreements.append(disagreement_rate)
max_disagreement = float(np.max(disagreements))
mean_disagreement = float(np.mean(disagreements))
return {
"discrepancy_bound": discrepancy_bound,
"discrepancy_extremal_pair": extremal_disagreement,
"discrepancy_empirical": mean_disagreement,
"max_pair_disagreement": max_disagreement,
"mean_pair_disagreement": mean_disagreement,
"threshold": tau,
}
[docs]
def capacity(self, delta: float | None = None) -> Dict[str, Any]:
"""Compute the capacity of the Rashomon set approximation.
Reports both the log-volume (continuous measure) and the delta-covering
number (discrete measure) of the approximating ellipsoid.
The delta-covering number N(delta, R_eps) counts how many balls of
radius delta are needed to cover R_eps. For the ellipsoid with
semi-axes ``a_j = sqrt(2*eps / lambda_j)``, it satisfies
``log N(delta) = sum_j log(max(a_j / delta, 1))``.
Parameters
----------
delta : float, optional
Covering radius for delta-covering computation. If None,
only log-volume is computed.
Returns
-------
dict with keys:
- 'log_volume': Log-volume of the ellipsoid approximation.
- 'effective_dim': Effective dimensionality (d).
- 'log_det_hessian': Log-determinant of the Hessian.
- 'log_covering_number': log N(delta) (only if delta is provided)
- 'delta': the delta used (only if provided)
"""
if not self._fitted or self._theta_hat is None or self._epsilon_value is None:
raise RuntimeError("Call fit() first")
# Use cached Cholesky L (H = L L^T)
# log(det(H)) = 2 * sum(log(diag(L)))
L = self._hessian_cholesky()
log_det_H = 2.0 * np.sum(np.log(np.diag(L)))
d = self._d
from scipy.special import gammaln
log_V_d = (d / 2.0) * np.log(np.pi) - gammaln(d / 2.0 + 1.0)
log_vol = log_V_d - 0.5 * log_det_H + (d / 2.0) * np.log(2.0 * self._epsilon_value)
result: Dict[str, Any] = {
"log_volume": float(log_vol),
"effective_dim": float(d),
"log_det_hessian": float(log_det_H),
}
if delta is not None:
delta = float(delta)
if delta <= 0:
raise ValueError("delta must be positive")
# Eigenvalues of H from Cholesky: H = L L^T, so eigenvalues of H
# are the squared singular values of L.
H = self._hessian_matrix()
eigvals = np.linalg.eigvalsh(H)
eigvals = np.maximum(eigvals, 1e-12)
# Semi-axes of the ellipsoid: a_j = sqrt(2*eps / lambda_j)
semi_axes = np.sqrt(2.0 * self._epsilon_value / eigvals)
# log N(delta) = sum_j log(max(a_j / delta, 1))
ratios = semi_axes / delta
log_covering = float(np.sum(np.log(np.maximum(ratios, 1.0))))
result["log_covering_number"] = log_covering
result["delta"] = delta
return result
[docs]
def multiplicity(
self,
X: Array,
which: tuple[str, ...] | list[str] = ("ambiguity", "discrepancy"),
y: Array | None = None,
samples: Array | None = None,
n_samples: int = 100,
threshold_mode: str = "fixed",
threshold_value: float | None = None,
**kwargs: Any,
) -> dict[str, Any]:
"""Compute predictive multiplicity metrics.
Unified interface for ambiguity, discrepancy, and other multiplicity measures.
Parameters
----------
X : Array
Data matrix.
which : tuple or list, default=("ambiguity", "discrepancy")
Which metrics to compute. Options: "ambiguity", "discrepancy", "capacity".
y : Array, optional
Labels (required for some threshold modes).
samples : Array, optional
Pre-computed parameter samples.
n_samples : int, default=100
Number of samples if not provided.
threshold_mode : str, default="fixed"
Threshold selection mode.
threshold_value : float, optional
Fixed threshold value.
**kwargs
Additional arguments passed to individual metric functions.
Returns
-------
metrics : dict
Dictionary with keys corresponding to requested metrics.
Examples
--------
>>> mult = rs.multiplicity(
... X_test, which=["ambiguity", "discrepancy"],
... threshold_mode="match_prevalence", y=y_test
... )
>>> print(f"Ambiguity: {mult['ambiguity']['ambiguity_rate']:.2%}")
>>> print(f"Discrepancy: {mult['discrepancy']['discrepancy_bound']:.2%}")
"""
result = {}
for metric in which:
if metric == "ambiguity":
result["ambiguity"] = self.ambiguity(
X,
threshold_mode=threshold_mode,
threshold_value=threshold_value,
y=y,
**kwargs,
)
elif metric == "discrepancy":
result["discrepancy"] = self.discrepancy(
X,
samples=samples,
n_samples=n_samples,
threshold_mode=threshold_mode,
threshold_value=threshold_value,
y=y,
**kwargs,
)
elif metric == "capacity":
result["capacity"] = self.capacity()
else:
warnings.warn(f"Unknown multiplicity metric: {metric}", stacklevel=2)
return result
[docs]
def compare_to_bootstrap(
self,
X: Array,
y: Array,
*,
n_bootstrap: int = 200,
n_rashomon: int = 200,
sampler: Optional[str] = None,
burnin: int = 100,
thin: int = 2,
confidence: float = 0.90,
feature_names: Optional[list] = None,
random_state: Optional[int] = None,
) -> Dict[str, Any]:
"""Compare bootstrap CIs to Rashomon set VIC intervals.
This method highlights the distinction between *sampling uncertainty*
(captured by bootstrap confidence intervals) and *design-choice
multiplicity* (captured by the Rashomon set's VIC intervals). The two
can diverge substantially: narrow CIs with wide VIC indicates many
near-optimal models despite well-identified parameters, while wide CIs
with narrow VIC means prediction is robust despite parameter uncertainty.
Parameters
----------
X : array of shape (n, d)
Feature matrix (same data used for fitting).
y : array of shape (n,)
Target vector.
n_bootstrap : int
Number of bootstrap resamples for CI estimation.
n_rashomon : int
Number of samples from the Rashomon set for VIC.
sampler : Optional[str]
Sampler for Rashomon set ("ellipsoid" or "hitandrun").
burnin : int
Burn-in for Hit-and-Run sampler.
thin : int
Thinning for Hit-and-Run sampler.
confidence : float
Confidence level for intervals (default 0.90).
feature_names : Optional[list]
Names of the features (without the intercept).
random_state : Optional[int]
Random seed for reproducibility.
Returns
-------
dict with keys:
- 'bootstrap_coefs': array (n_bootstrap, d) - bootstrap coefficient samples
- 'bootstrap_ci': array (d, 2) - bootstrap confidence intervals
- 'bootstrap_mean': array (d,) - bootstrap mean coefficients
- 'bootstrap_std': array (d,) - bootstrap std of coefficients
- 'vic_samples': array (n_rashomon, d) - Rashomon set coefficient samples
- 'vic_intervals': array (d, 2) - VIC intervals at same confidence
- 'vic_mean': array (d,) - VIC mean coefficients
- 'vic_std': array (d,) - VIC std of coefficients
- 'theta_hat': array (d,) - point estimate
- 'feature_names': list - feature names
- 'confidence': float - confidence level used
- 'divergence': dict with per-feature comparison metrics
"""
if not self._fitted or self._theta_hat is None or self._epsilon_value is None:
raise RuntimeError("Call fit() first.")
X_raw = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float)
n = X_raw.shape[0]
d = self._d_original if self.fit_intercept else self._d
seed = self._seed if random_state is None else int(random_state)
rng = np.random.default_rng(seed)
alpha = 1.0 - confidence
# --- Bootstrap resampling ---
# Refit the same objective (same lambda, same penalty mask) on each resample.
X_boot_source = self._prepare_X(X_raw) if self.fit_intercept else X_raw
boot_coefs = np.zeros((n_bootstrap, d), dtype=float)
lam = float(self._lambda) if self._lambda is not None else 0.0
mask = self._reg_mask_or_ones()
sw_all = self._sw_or_ones()
for b in range(n_bootstrap):
idx = rng.choice(n, size=n, replace=True)
X_b, y_b, sw_b = X_boot_source[idx], y[idx], sw_all[idx]
try:
if self.estimator == "logistic":
coef, _L, _w = self._fit_logistic_l2(X_b, y_b, lam, mask, theta_init=self._theta_hat, sw=sw_b)
else:
coef, _L = self._fit_linear_ridge(X_b, y_b, lam, mask, sw=sw_b)
boot_coefs[b] = coef[1:] if self.fit_intercept else coef
except Exception:
boot_coefs[b] = self.coef_
boot_mean = np.mean(boot_coefs, axis=0)
boot_std = np.std(boot_coefs, axis=0)
boot_ci = np.stack([
np.quantile(boot_coefs, alpha / 2, axis=0),
np.quantile(boot_coefs, 1 - alpha / 2, axis=0),
], axis=1)
# --- Rashomon set VIC ---
vic = self.variable_importance_cloud(
n_samples=n_rashomon,
sampler=sampler,
feature_names=feature_names,
burnin=burnin,
thin=thin,
random_state=seed,
)
vic_samples = vic["samples"]
# Slice out the intercept column for comparison with bootstrap
if self.fit_intercept:
vic_samples = vic_samples[:, 1:]
vic_mean = np.mean(vic_samples, axis=0)
vic_std = np.std(vic_samples, axis=0)
q_lo = alpha / 2
q_hi = 1 - alpha / 2
vic_intervals = np.stack([
np.quantile(vic_samples, q_lo, axis=0),
np.quantile(vic_samples, q_hi, axis=0),
], axis=1)
# --- Per-feature divergence metrics (features only; the intercept was sliced out) ---
names = vic["feature_names"][1:] if self.fit_intercept else vic["feature_names"]
divergence = {}
for j in range(d):
boot_width = float(boot_ci[j, 1] - boot_ci[j, 0])
vic_width = float(vic_intervals[j, 1] - vic_intervals[j, 0])
# Overlap between the two intervals
overlap_lo = max(boot_ci[j, 0], vic_intervals[j, 0])
overlap_hi = min(boot_ci[j, 1], vic_intervals[j, 1])
overlap = max(0.0, float(overlap_hi - overlap_lo))
union_width = max(boot_ci[j, 1], vic_intervals[j, 1]) - min(boot_ci[j, 0], vic_intervals[j, 0])
iou = overlap / union_width if union_width > 0 else 1.0
divergence[names[j]] = {
"bootstrap_width": boot_width,
"vic_width": vic_width,
"width_ratio": vic_width / boot_width if boot_width > 1e-12 else float("inf"),
"overlap_iou": iou,
}
return {
"bootstrap_coefs": boot_coefs,
"bootstrap_ci": boot_ci,
"bootstrap_mean": boot_mean,
"bootstrap_std": boot_std,
"vic_samples": vic_samples,
"vic_intervals": vic_intervals,
"vic_mean": vic_mean,
"vic_std": vic_std,
"theta_hat": self._theta_hat.copy(),
"feature_names": names,
"confidence": confidence,
"divergence": divergence,
}
[docs]
def compare_to_bayesian(
self,
*,
n_samples: int = 500,
confidence: float = 0.90,
feature_names: Optional[list] = None,
random_state: Optional[int] = None,
) -> Dict[str, Any]:
"""Compare the Rashomon set to the Laplace posterior of the fitted model.
The fitted objective is ``L(θ) = mean loss + (λ/2) θᵀMθ``, so ``n·L(θ)`` is a
negative log-posterior: the (weighted) log-likelihood plus a Gaussian prior
with precision ``nλ`` on the penalized coordinates and a flat prior on the
others. ``θ̂`` is the mode of that posterior, and its Laplace approximation is
``N(θ̂, (nH)⁻¹)`` with ``H = ∇²L(θ̂)``, the Hessian used throughout this class.
For an unpenalized fit this is the usual asymptotic (Wald) distribution of the
MLE. For linear models the loss is the Gaussian negative log-likelihood with
unit noise variance, so the posterior is in those units.
To second order the ε-Rashomon set ``{θ : L(θ) ≤ L(θ̂) + ε}`` is the
highest-posterior-density region ``{θ : (θ-θ̂)ᵀ nH (θ-θ̂) ≤ 2nε}`` of this
posterior, whose posterior mass is ``F_{χ²_d}(2nε)`` (returned as
``hpd_level``). Its projection onto coordinate ``j`` is
``θ̂_j ± sqrt(2nε)·sd_j`` while the marginal ``(1-α)`` credible interval is
``θ̂_j ± z_{1-α/2}·sd_j``, so under the quadratic approximation the ratio
of the Rashomon coefficient range to the credible interval is
``sqrt(2nε)/z_{1-α/2}`` for every coordinate. The exact Rashomon ranges
differ from this only by the non-quadratic part of the loss inside the set.
Parameters
----------
n_samples : int
Samples from both the posterior and the Rashomon set.
confidence : float
Level of the marginal credible intervals and of the VIC quantile
intervals (default 0.90).
feature_names : Optional[list]
Names of the features, or of all coordinates including the intercept.
random_state : Optional[int]
Seed.
Returns
-------
dict with:
- 'bayesian_samples': (n_samples, d) - posterior samples
- 'bayesian_ci': (d, 2) - marginal credible intervals at ``confidence``
- 'bayesian_std': (d,) - marginal posterior std
- 'rashomon_range': (d, 2) - coefficient ranges over the Rashomon set
(exact when ``n·d² ≤ 5·10⁶``, otherwise the Hessian ellipsoid)
- 'rashomon_range_method': "exact" or "ellipsoid"
- 'vic_samples': (n_samples, d) - uniform samples of the Rashomon set
- 'vic_intervals': (d, 2) - quantile intervals of those samples at ``confidence``
- 'vic_std': (d,) - std of those samples
- 'theta_hat': (d,) - the fitted parameters (posterior mode)
- 'feature_names': list
- 'confidence': float
- 'hpd_level': posterior mass of the Rashomon set under the quadratic
approximation, ``F_{χ²_d}(2nε)``
- 'comparison': dict - per-coordinate widths and ratios
- 'posterior_precision': (d, d) - ``nH``
- 'epsilon_vs_chi2': dict - the Rashomon radius ``2ε`` against the radius
``χ²_{d,1-α}/n`` of the ``(1-α)`` credible ellipsoid, both in the H-norm,
plus the quadratic-approximation ratio ``sqrt(2nε)/z_{1-α/2}``
"""
if not self._fitted or self._theta_hat is None or self._epsilon_value is None:
raise RuntimeError("Call fit() first.")
d = self._d
n = self._n
eps = float(self._epsilon_value)
alpha = 1.0 - confidence
seed = self._seed if random_state is None else int(random_state)
rng = np.random.default_rng(seed)
# Posterior precision: n * Hessian of the mean-loss objective. The prior that
# makes theta_hat the MAP has precision n*lambda, which is already inside H.
H_posterior = n * self._hessian_matrix()
eigvals_post = np.linalg.eigvalsh(H_posterior)
if np.min(eigvals_post) < 1e-10:
H_posterior = H_posterior + (1e-8 - np.min(eigvals_post)) * np.eye(d)
Sigma_posterior = np.linalg.inv(H_posterior)
# Sample from the Laplace posterior N(theta_hat, Sigma_posterior)
L_post = np.linalg.cholesky(Sigma_posterior)
z_samples = rng.normal(size=(n_samples, d))
bayesian_samples = self._theta_hat[None, :] + z_samples @ L_post.T
# Marginal credible intervals
from scipy.stats import norm as _norm
z_crit = float(_norm.ppf(1.0 - alpha / 2))
posterior_std = np.sqrt(np.diag(Sigma_posterior))
bayesian_ci = np.stack([
self._theta_hat - z_crit * posterior_std,
self._theta_hat + z_crit * posterior_std,
], axis=1)
# Coefficient ranges over the Rashomon set: exact when affordable
if n * d * d <= 5e6:
rashomon_range = self.coef_extremes()
range_method = "exact"
else:
rashomon_range = self.coef_intervals()
range_method = "ellipsoid"
# Uniform samples of the set (VIC)
vic = self.variable_importance_cloud(
n_samples=n_samples,
feature_names=feature_names,
random_state=seed,
)
vic_samples = vic["samples"]
vic_intervals = np.stack([
np.quantile(vic_samples, alpha / 2, axis=0),
np.quantile(vic_samples, 1 - alpha / 2, axis=0),
], axis=1)
vic_std = np.std(vic_samples, axis=0)
quadratic_ratio = float(np.sqrt(2.0 * n * eps)) / z_crit
names = vic["feature_names"]
comparison = {}
for j in range(d):
bayes_width = float(bayesian_ci[j, 1] - bayesian_ci[j, 0])
vic_width = float(vic_intervals[j, 1] - vic_intervals[j, 0])
range_width = float(rashomon_range[j, 1] - rashomon_range[j, 0])
comparison[names[j]] = {
"bayesian_width": bayes_width,
"range_width": range_width,
"range_to_bayesian_ratio": range_width / bayes_width if bayes_width > 1e-12 else float("inf"),
"range_to_bayesian_ratio_quadratic": quadratic_ratio,
"vic_width": vic_width,
"vic_to_bayesian_ratio": vic_width / bayes_width if bayes_width > 1e-12 else float("inf"),
"bayesian_std": float(posterior_std[j]),
"vic_std": float(vic_std[j]),
}
# Both regions are ellipsoids in the H-norm (to second order for the Rashomon
# set): radius^2 = 2*eps for the Rashomon set, chi2_{d,1-alpha}/n for the
# (1-alpha) credible ellipsoid.
rashomon_radius_sq = 2.0 * eps
if _HAS_SCIPY:
posterior_radius_sq = float(chi2.ppf(1.0 - alpha, df=d)) / n
hpd_level = float(chi2.cdf(2.0 * n * eps, df=d))
else:
posterior_radius_sq = hpd_level = float("nan")
epsilon_vs_chi2 = {
"rashomon_radius_sq": float(rashomon_radius_sq),
"posterior_radius_sq_per_n": posterior_radius_sq,
"rashomon_wider": float(rashomon_radius_sq) > posterior_radius_sq,
"hpd_level": hpd_level,
"range_to_bayesian_ratio_quadratic": quadratic_ratio,
}
return {
"bayesian_samples": bayesian_samples,
"bayesian_ci": bayesian_ci,
"bayesian_std": posterior_std,
"rashomon_range": rashomon_range,
"rashomon_range_method": range_method,
"vic_samples": vic_samples,
"vic_intervals": vic_intervals,
"vic_std": vic_std,
"theta_hat": self._theta_hat.copy(),
"feature_names": names,
"confidence": confidence,
"hpd_level": hpd_level,
"comparison": comparison,
"posterior_precision": H_posterior,
"epsilon_vs_chi2": epsilon_vs_chi2,
}
[docs]
@classmethod
def from_ensemble(
cls,
models: list,
X: Array,
y: Array,
*,
estimator: str = "logistic",
lam: float = 0.0,
feature_names: Optional[list] = None,
) -> Dict[str, Any]:
"""Compute Rashomon-style metrics from an external model ensemble.
Takes a collection of fitted models (parameter vectors or sklearn-style
objects) and computes VIC, MCR, ambiguity, and discrepancy without
fitting a new RashomonSet. This enables analysis of any external
model collection (grid search, dropout ensembles, random seeds, etc.).
Parameters
----------
models : list
List of parameter vectors (array of shape (d,)) or sklearn-style
objects with .coef_ attribute.
X : array (n, d)
Feature matrix.
y : array (n,)
Target vector.
estimator : str
Model type ("logistic" or "linear").
lam : float
Regularization strength (lambda). Include this to make losses
comparable to RashomonSet.L_hat. Default 0 computes data loss only.
feature_names : Optional[list]
Names of the features, or of all coordinates including the intercept.
Returns
-------
dict with:
- 'n_models': number of models in ensemble
- 'coef_matrix': (n_models, d) array of coefficient vectors
- 'vic_mean': (d,) mean coefficients
- 'vic_std': (d,) std of coefficients
- 'vic_intervals': (d, 2) 90% intervals
- 'losses': (n_models,) regularized loss for each model
- 'ambiguity_rate': fraction of instances with disagreeing predictions
- 'max_pair_disagreement': max pairwise disagreement
- 'feature_names': list
"""
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float)
n, d = X.shape
lam = float(lam)
# Extract coefficient vectors
coefs = []
for m in models:
if hasattr(m, "coef_"):
coefs.append(np.asarray(m.coef_).ravel())
else:
coefs.append(np.asarray(m, dtype=float).ravel())
coef_matrix = np.array(coefs, dtype=float)
n_models = coef_matrix.shape[0]
# Compute regularized losses (comparable to RashomonSet L_hat)
losses = np.zeros(n_models, dtype=float)
for i, theta in enumerate(coef_matrix):
z = X @ theta
reg = 0.5 * lam * float(np.dot(theta, theta))
if estimator == "logistic":
losses[i] = float(np.mean(np.logaddexp(0.0, z) - y * z)) + reg
else:
losses[i] = float(0.5 * np.mean((y - z) ** 2)) + reg
# VIC statistics
vic_mean = np.mean(coef_matrix, axis=0)
vic_std = np.std(coef_matrix, axis=0)
vic_intervals = np.stack([
np.quantile(coef_matrix, 0.05, axis=0),
np.quantile(coef_matrix, 0.95, axis=0),
], axis=1)
# Ambiguity: fraction of instances where models disagree
if estimator == "logistic":
margins = X @ coef_matrix.T # (n, n_models)
preds = (margins >= 0.0).astype(int)
else:
preds = (X @ coef_matrix.T >= np.median(y)).astype(int)
# Instance is ambiguous if not all models agree
ambiguous = np.any(preds != preds[:, 0:1], axis=1)
ambiguity_rate = float(np.mean(ambiguous))
# Max pairwise disagreement
max_disagree = 0.0
n_check = min(n_models * (n_models - 1) // 2, 500)
rng = np.random.default_rng(0)
if n_models >= 2:
for _ in range(n_check):
i, j = rng.choice(n_models, size=2, replace=False)
dis = float(np.mean(preds[:, i] != preds[:, j]))
max_disagree = max(max_disagree, dis)
names = feature_names if feature_names is not None else [f"feature_{i}" for i in range(d)]
return {
"n_models": n_models,
"coef_matrix": coef_matrix,
"vic_mean": vic_mean,
"vic_std": vic_std,
"vic_intervals": vic_intervals,
"losses": losses,
"ambiguity_rate": ambiguity_rate,
"max_pair_disagreement": max_disagree,
"feature_names": list(names),
}
def _detect_blas_vendor() -> Optional[str]:
try:
import numpy as _np # noqa: F401
from numpy import __config__ as _nc
info = getattr(_nc, "blas_opt_info", None)
if isinstance(info, dict) and info:
libs = info.get("libraries") or []
if libs:
return ",".join(libs)
return os.environ.get("MKL_SERVICE_FORCE_INTEL", None) or platform.system()
except Exception: # pragma: no cover
return None