API Reference

rashomon.audit

rashomon.audit(model: Any, X: Any, y: Any, *, tolerance: str | float | Tuple[str, float] = 'cv', threshold: float | None | str = 'auto', n_samples: int = 1000, cv: int = 5, method: str = 'auto', exact_ranges: bool | str = 'auto', exact_flips: bool | str = 'auto', sample_weight: Any = None, random_state: int | None = None, feature_names: Sequence[str] | None = None) → StabilityReport[source]

Audit whether a fitted scikit-learn linear model’s conclusions survive equally-good models.

Parameters:
  • model (fitted estimator) – LogisticRegression / LogisticRegressionCV (binary, L2 or unpenalized), Ridge / RidgeCV, LinearRegression, or a Pipeline ending in one of these (the preprocessing steps are applied to X).

  • X (array-like or pandas) – The training data the model was fitted on. Feature names are taken from X.columns or the pipeline when available.

  • y (array-like or pandas) – The training data the model was fitted on. Feature names are taken from X.columns or the pipeline when available.

  • tolerance ("cv" | float | "lr" | ("lr", alpha) | ("absolute", gap), default "cv") –

    What “equally good” means:

    • "cv": a training-loss gap of one cross-validation standard error of the held-out loss (the one-standard-error rule from glmnet). Costs cv extra fits of the model.

    • a float r in (0, 1): a loss gap of r times the optimal training loss (0.01 means models at most 1% worse).

    • "lr" / ("lr", alpha): likelihood-ratio calibration, the set of models not rejected at level alpha (default 0.05). Exact for unpenalized fits, a heuristic under regularization.

    • ("profile", alpha): a gap of chi2_1(1 - alpha) / (2n). For an unpenalized fit the coefficient ranges are then the 1 - alpha profile-likelihood confidence intervals (as from R’s confint).

    • ("absolute", gap): a loss gap in training-loss units.

  • threshold (float, None or "auto", default "auto") – Decision threshold on the predicted probability (classification; "auto" means 0.5, as in model.predict) or on the fitted value (regression; "auto" means None, i.e. no flip analysis unless a cutoff is given).

  • n_samples (int, default 1000) – Number of equally-good models to sample. More samples tighten ranges and raise the effective sample size.

  • cv (int, default 5) – Folds used by tolerance="cv".

  • method ("auto" | "sample" | "ellipsoid", default "auto") – "sample" (what "auto" chooses) draws from the exact set with a hit-and-run chain plus ellipsoid proposals. "ellipsoid" draws i.i.d. from the Hessian ellipsoid and keeps the draws that are in the set; faster, but it cannot reach parts of the set outside the ellipsoid.

  • exact_ranges (bool or "auto", default "auto") – Compute coefficient ranges (and so sign_stable) by convex optimization over the true set instead of from the sampled models. Costs a few dozen Hessian builds per coefficient; "auto" does it whenever n * n_features**2 <= 5e6.

  • exact_flips (bool or "auto", default "auto") – Decide each row’s flip exactly: rows already flipped by a sampled model are settled; every other row is tested with one convex program (RashomonSet.can_flip). "auto" does it whenever n_undecided * n * n_features**2 <= 1e9; otherwise the flip rate is over the sampled models and labelled as a lower bound.

  • sample_weight (array-like of shape (n,), optional) – The sample_weight the model was fitted with, if any. class_weight is read from the model itself. Weights change which models count as equally good (the weighted training loss); row counts in the report stay unweighted.

  • random_state (int, optional)

  • feature_names (sequence of str, optional) – Overrides inferred names.

Return type:

StabilityReport

rashomon.StabilityReport

class rashomon.StabilityReport(model_name: str, task: str, n: int, n_features: int, feature_names: ~typing.List[str], tolerance: float, tolerance_description: str, loss_name: str, loss_optimum: float, method: str, n_models: int, ess_min: float | None, reliability: str, threshold: float | None, flip_rate: float | None, n_flipped: int | None, flipped: ~numpy.ndarray, max_disagreement: float | None, flip_method: str, coefficients: ~pandas.DataFrame, coefficient_ranges: str, intercept: float | None, intercept_range: ~typing.Tuple[float, float] | None, prediction_ranges: ~pandas.DataFrame, runtime_seconds: float, _rs: ~rashomon.rashomon_set.RashomonSet, _samples: ~numpy.ndarray, details: ~typing.Dict[str, ~typing.Any] = <factory>)[source]

Result of audit().

The term used for each quantity in the literature is given in brackets.

Variables:
  • flip_rate (float or None) – Fraction of rows whose predicted label changes under some equally-good model [ambiguity, Marx, Calmon & Ustun 2020]. None for regression without a threshold. Exact when flip_method == "exact" (each undecided row is tested by a convex program); otherwise over sampled models.

  • flipped (ndarray of bool, shape (n,)) – Row mask of those predictions.

  • max_disagreement (float or None) – Largest fraction of rows on which a single equally-good model disagrees with your model [discrepancy, Marx et al. 2020]. Over sampled models; always <= flip_rate.

  • coefficients (DataFrame indexed by feature) – estimate (your model), low/high (range across equally-good models) and sign_stable (the range excludes zero) [variable importance cloud, Dong & Rudin 2020; hacking intervals, Coker, Rudin & King 2021]. When coefficient_ranges == "exact" the range is the solution of a convex program over the true set; otherwise it is the range over sampled models.

  • prediction_ranges (DataFrame) – Per-row estimate (probability or fitted value), low, high and flipped, over the sampled models.

  • tolerance (float) – The loss gap defining “equally good”, in the units of the training loss.

  • reliability (ess_min,) – Minimum effective sample size across coefficients and its label (reliable / fair / unreliable).

  • and (Quantities computed over sampled models (disagreement, prediction ranges,)

  • bounds (flip rate or coefficient ranges when not exact) are lower)

  • to (model is in the set, but the set is not exhausted. Increase n_samples)

  • them. (tighten)

coefficient_ranges: str
coefficients: DataFrame
details: Dict[str, Any]
ess_min: float | None
feature_names: List[str]
flip_method: str
flip_rate: float | None
flipped: ndarray
intercept: float | None
intercept_range: Tuple[float, float] | None
loss_name: str
loss_optimum: float
max_disagreement: float | None
method: str
model_name: str
n: int
n_features: int
n_flipped: int | None
n_models: int
plot(max_features: int = 30, max_rows: int = 2000, figsize: Tuple[float, float] | None = None) → Any[source]

One figure: prediction ranges per row (left) and coefficient ranges (right).

predict_ranges(X: Any, exact_flips: bool | None = None) → DataFrame[source]

Prediction ranges and flips for new rows.

Ranges come from the sampled models. Flips are exact (one convex program per row not already flipped by a sampled model) when exact_flips is True, or by default whenever the report’s own flips were exact.

prediction_ranges: DataFrame
property rashomon_set: RashomonSet

The underlying RashomonSet (expert API).

reliability: str
runtime_seconds: float
property samples: ndarray

Sampled parameter vectors, shape (n_models, d [+1 with intercept]); intercept first.

property stable_features: List[str]
summary() → str[source]

Text summary. print(report.summary()) or just report.

task: str
threshold: float | None
tolerance: float
tolerance_description: str
property unstable_features: List[str]

rashomon.RashomonSet

class rashomon.RashomonSet(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: int | None = None, max_iter: int = 1000, tol: float = 1e-06, safety_override: bool = False, bootstrap_fallback: bool = True, bootstrap_reps: int = 200, penalize_intercept: bool = False)[source]

Bases: object

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 rashomon.audit() or 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%}")
ambiguity(X: ndarray, threshold_mode: str = 'fixed', threshold_value: float | None = None, y: ndarray | None = None, **kwargs: Any) → dict[str, Any][source]

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 –

  • “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

Return type:

dict

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%}")
can_flip(X: ndarray, tau: float = 0.0, coef_box: ndarray | None = None) → ndarray[source]

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 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, _hyperplane_flip_tests() for logistic).

capacity(delta: float | None = None) → Dict[str, Any][source]

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:

  • ‘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)

Return type:

dict with keys

property coef_: ndarray
coef_extremes(indices: ndarray | None = None) → ndarray[source]

Exact per-coordinate [min, max] over the ε-Rashomon set (see functional_range()).

Returns an array of shape (m, 2); coordinates include the intercept (index 0) when fit_intercept=True.

coef_intervals(indices: ndarray | None = None) → ndarray[source]

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:

Interval bounds for selected m coordinates in the order given.

Return type:

np.ndarray of shape (m, 2)

compare_to_bayesian(*, n_samples: int = 500, confidence: float = 0.9, feature_names: list | None = None, random_state: int | None = None) → Dict[str, Any][source]

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:

  • ‘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}

Return type:

dict with

compare_to_bootstrap(X: ndarray, y: ndarray, *, n_bootstrap: int = 200, n_rashomon: int = 200, sampler: str | None = None, burnin: int = 100, thin: int = 2, confidence: float = 0.9, feature_names: list | None = None, random_state: int | None = None) → Dict[str, Any][source]

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:

  • ‘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

Return type:

dict with keys

compute_sample_diagnostics(samples: ndarray, *, burnin: int = 0, compute_ess: bool = True, compute_isotropy: bool = True) → Dict[str, Any][source]

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:

  • ‘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)

Return type:

dict with keys

compute_threshold(y: ndarray, mode: str = 'fixed', value: float | None = None, **kwargs: Any) → float[source]

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 – Decision threshold in margin space (x^T theta).

Return type:

float

Examples

>>> rs.compute_threshold(y, mode="fixed", value=0.5)
0.0
>>> rs.compute_threshold(y, mode="match_prevalence")
-0.123
contains(theta: ndarray, atol: float = 1e-12, *, x_theta: ndarray | None = None) → bool[source]

Return True if θ is inside the ε-Rashomon set: L(θ) - L(θ̂) ≤ ε.

contains_many(Theta: ndarray, atol: float = 1e-12, *, XTheta: ndarray | None = None) → ndarray[source]

Vectorized membership oracle: return mask of rows inside ε-set.

Returns a boolean array of shape (k,).

decision_function(X: ndarray) → ndarray[source]
diagnostics() → Dict[str, Any][source]
discrepancy(X: ndarray, samples: ndarray | None = None, n_samples: int = 100, n_pairs: int = 50, threshold_mode: str = 'fixed', threshold_value: float | None = None, y: ndarray | None = None, random_state: int | None = None, **kwargs: Any) → dict[str, Any][source]

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 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 –

  • “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

Return type:

dict

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%}")
fit(X: ndarray, y: ndarray, *, theta_init: ndarray | None = None, sample_weight: ndarray | None = None) → RashomonSet[source]

Fit the base GLM and prepare diagnostics and operators.

Parameters:
  • X (arrays) – Training data. For logistic models y must be in {0, 1}.

  • 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.

classmethod from_ensemble(models: list, X: ndarray, y: ndarray, *, estimator: str = 'logistic', lam: float = 0.0, feature_names: list | None = None) → Dict[str, Any][source]

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:

  • ‘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

Return type:

dict with

classmethod from_sklearn(model: Any, X: ndarray, y: ndarray, *, sample_weight: ndarray | None = None, **kwargs: Any) → RashomonSet[source]

Build a 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 (training data (X may be a pandas DataFrame))

  • 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 RashomonSet (e.g. epsilon, epsilon_mode,) – random_state). estimator, C, fit_intercept and penalize_intercept are derived from model and cannot be overridden.

functional_range(s: ndarray) → Tuple[float, float][source]

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). 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.

get_params(deep: bool = True) → Dict[str, Any][source]
hacking_interval(s: ndarray) → Dict[str, float][source]
property intercept_: float

Intercept term (0.0 if fit_intercept=False).

loss_gap(theta: ndarray, *, x_theta: ndarray | None = None) → float[source]

Return L(θ) - L(θ̂).

loss_gap_many(Theta: ndarray, *, XTheta: ndarray | None = None) → ndarray[source]

Vectorized loss gap: L(θ_j) - L(θ̂) for rows of Theta.

mcr_analytic(X: ndarray, y: ndarray, *, n_permutations: int = 20, score_fn: str = 'loss', random_state: int | None = None) → Dict[str, Any][source]

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 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:

  • ‘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

Return type:

dict with

min_loss_on_hyperplane(s: ndarray, c: float, theta0: ndarray | None = None) → float[source]

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.

model_class_reliance(X: ndarray, y: ndarray, *, n_permutations: int = 16, n_samples: int = 100, perm_mode: str = 'iid', sampler: str | None = None, burnin: int = 100, thin: int = 2, check_collinearity: bool = True, random_state: int | None = None, metric: str = 'score') → Dict[str, Any][source]

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.”

multiplicity(X: ndarray, which: tuple[str, ...] | list[str] = ('ambiguity', 'discrepancy'), y: ndarray | None = None, samples: ndarray | None = None, n_samples: int = 100, threshold_mode: str = 'fixed', threshold_value: float | None = None, **kwargs: Any) → dict[str, Any][source]

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 – Dictionary with keys corresponding to requested metrics.

Return type:

dict

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%}")
property n_features_in_: int
objective(theta: ndarray, *, x_theta: ndarray | None = None) → float[source]

Compute penalized objective L(θ) at parameter θ.

L(θ) = average loss + (λ/2)||θ||^2

objective_many(Theta: ndarray, *, XTheta: ndarray | None = None) → ndarray[source]

Vectorized penalized objective for a batch of parameters.

Parameters:

Theta (array-like of shape (k, d)) – Rows are parameter vectors θ_j.

Returns:

Values L(θ_j) for each row.

Return type:

np.ndarray of shape (k,)

plot_ambiguity(X: ndarray, threshold_mode: str = 'fixed', threshold_value: float | None = None, y: ndarray | None = None, figsize: tuple | None = None, **kwargs: Any) → Any[source]

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.

Return type:

fig, ax

plot_discrepancy(X: ndarray, samples: ndarray | None = None, n_samples: int = 50, n_pairs: int = 100, threshold_mode: str = 'fixed', threshold_value: float | None = None, y: ndarray | None = None, figsize: tuple | None = None, **kwargs: Any) → Any[source]

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.

Return type:

fig, ax

plot_vic(vic_result: Dict[str, Any] | None = None, *, n_samples: int = 200, feature_names: list | None = None, figsize: tuple | None = None, show_theta_hat: bool = True, **kwargs: Any) → Any[source]

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().

Return type:

matplotlib Figure and Axes objects.

predict(X: ndarray) → ndarray[source]
predict_proba(X: ndarray) → ndarray[source]
probability_bands(X: ndarray) → ndarray[source]

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].

quadratic_error(S: ndarray | None = None, method: str = 'ray', steps: int = 1) → ndarray[source]

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:

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.

Return type:

np.ndarray of shape (m, 2)

sample(n_samples: int = 100, **kwargs: Any) → ndarray[source]

Sample parameters using the configured sampler backend.

sample_ellipsoid(n_samples: int = 100, random_state: int | None = None) → ndarray[source]

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).

sample_hitandrun(n_samples: int = 100, *, burnin: int = 200, thin: int = 1, directions: str | None = None, precondition: bool | None = None, t_init: float = 1.0, growth: float = 2.0, max_bracket: float = 1000000.0, max_bisect: int = 50, tol: float = 1e-10, random_state: int | None = None, compute_diagnostics: bool = True, ellipsoid_mix: float = 0.0) → ndarray[source]

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).

score(X: ndarray, y: ndarray) → float[source]

Sklearn-style score: accuracy (logistic) or R^2 (linear).

set_params(**params: Any) → RashomonSet[source]
shapley_vic(X: ndarray, *, n_samples: int = 200, sampler: str | None = None, feature_names: list | None = None, burnin: int = 100, thin: int = 2, random_state: int | None = None) → Dict[str, Any][source]

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 (int) – Hit-and-Run parameters.

  • thin (int) – Hit-and-Run parameters.

  • random_state (Optional[int]) – Seed.

Returns:

  • ‘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

Return type:

dict with

variable_importance(mode: str = 'VIC') → Any[source]

Deprecated: use variable_importance_cloud() instead.

variable_importance_cloud(*, n_samples: int = 200, sampler: str | None = None, feature_names: list | None = None, burnin: int = 100, thin: int = 2, random_state: int | None = None) → Dict[str, Any][source]

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:

  • ‘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

Return type:

dict with keys

rashomon.plotting

Visualization utilities for Rashomon set stability analysis.

rashomon.plotting.plot_ambiguity(margins: ndarray, threshold: float = 0.0, ambiguous_indices: ndarray | None = None, bins: int = 30, figsize: Tuple[float, float] | None = (10, 6)) → Tuple[Figure, Axes][source]

Plot distribution of predictive margins and highlight ambiguity region.

Parameters:
  • margins (array) – Predictive margins (x^T theta_hat) for instances.

  • threshold (float) – Decision threshold in margin space.

  • ambiguous_indices (array, optional) – Indices of instances flagged as ambiguous.

Return type:

fig, ax

rashomon.plotting.plot_discrepancy(discrepancy_matrix: ndarray, sample_indices: List[int] | None = None, figsize: Tuple[float, float] | None = (8, 7)) → Tuple[Figure, Axes][source]

Plot pairwise discrepancy matrix between sampled models.

Parameters:

discrepancy_matrix (array of shape (n_samples, n_samples)) – Pairwise disagreement rates.

Return type:

fig, ax

rashomon.plotting.plot_vic(vic_result: Dict[str, Any], theta_hat: ndarray | None = None, figsize: Tuple[float, float] | None = None) → Tuple[Figure, Axes][source]

Plot coefficient distributions across the Rashomon set.

Parameters:
  • vic_result (dict) – Result from RashomonSet.variable_importance_cloud().

  • theta_hat (array, optional) – Optimal parameter vector to highlight.

  • figsize (tuple, optional) – Figure size.

Returns:

fig, ax

Return type:

matplotlib objects