API Reference

Complete reference for the public API of rank_preserving_calibration.

Core Functions

rank_preserving_calibration.diagnose(probs: ArrayLike, target_shares: ArrayLike, *, row_weights: ArrayLike | None = None, top_k: int = 5, tol: float = 1e-09) → DiagnosisResult[source]

Diagnose whether standard IPF reverses within-class rankings.

Runs weighted Iterative Proportional Fitting (IPF) to match target_shares and reports how large the marginal shift is, how many within-class pairs IPF reverses, and the top_k largest reversals.

Parameters:
  • probs – Predicted probability matrix of shape (N, J).

  • target_shares – Target class proportions of shape (J,) summing to 1.0.

  • row_weights – Optional positive row weights of shape (N,) (e.g., poststratification cell counts or survey weights).

  • top_k – Number of largest reversed pairs to include in worst_reversals.

  • tol – IPF convergence tolerance.

Returns:

DiagnosisResult with IPF probabilities, multipliers, shift magnitude, and rank-reversal diagnostics.

Raises:

CalibrationError – If inputs are invalid.

rank_preserving_calibration.calibrate(probs: ArrayLike, target_shares: ArrayLike, *, rank_penalty: float | None = None, row_weights: ArrayLike | None = None, reference: ArrayLike | None = None, anchor: ArrayLike | None = None, ties: Literal['weak', 'stable'] = 'weak', loss: Literal['kl', 'euclidean'] = 'kl', tol: float = 1e-09, verbose: bool = False) → CalibrationResult[source]

Calibrate multiclass probabilities to match target class shares.

Finds a probability matrix Q whose rows sum to 1 and whose weighted column averages equal target_shares, minimizing weighted KL divergence (or squared Euclidean distance) from reference subject to within-class weak-order constraints anchored to anchor.

Control rank preservation with a single continuous dial rank_penalty:

  • rank_penalty=None (default): strict weak-order preservation (zero rank reversals).

  • rank_penalty=0.0: unconstrained marginal matching (weighted IPF under loss="kl").

  • rank_penalty > 0: soft weak-order calibration charging rank_penalty per unit of L1 rank violation (e.g., 1.0).

Parameters:
  • probs – Predicted probability matrix of shape (N, J).

  • target_shares – Target class proportions of shape (J,) summing to 1.0.

  • rank_penalty – None for strict rank preservation, 0.0 for unconstrained marginal matching, or a positive float for soft rank regularization.

  • row_weights – Optional strictly positive row weights of shape (N,) (e.g., poststratification cell counts or survey weights).

  • reference – Optional reference probability matrix R of shape (N, J) from which divergence is measured. Defaults to probs. Use with apply_temperature() to decouple source recalibration from the ranking anchor.

  • anchor – Optional score matrix A of shape (N, J) defining the within-class order to preserve. Defaults to probs.

  • ties – "weak" (default) uses permutation-invariant block-boundary constraints so tied anchor scores are unconstrained relative to each other; "stable" imposes row-index order among ties.

  • loss – "kl" (default, multiplicative exponential-cone solve) or "euclidean" (exact sparse quadratic program).

  • tol – Solver convergence tolerance.

  • verbose – If True, print solver progress.

Returns:

CalibrationResult containing calibrated probabilities and feasibility/rank diagnostics.

Raises:

CalibrationError – If inputs are invalid or strict rank preservation cannot be certified.

rank_preserving_calibration.pareto(probs: ArrayLike, target_shares: ArrayLike, *, lambdas: Sequence[float] | np.ndarray | None = None, row_weights: ArrayLike | None = None, reference: ArrayLike | None = None, anchor: ArrayLike | None = None, ties: Literal['weak', 'stable'] = 'weak', loss: Literal['kl', 'euclidean'] = 'kl', tol: float = 1e-09, verbose: bool = False) → ParetoResult[source]

Trace the accuracy vs. rank-preservation Pareto frontier across lambdas.

Solves calibrate() over a sorted grid of rank penalties—by default spanning 0.0 (unconstrained IPF) through soft penalties to inf (strict weak-order preservation).

Parameters:
  • probs – Predicted probability matrix of shape (N, J).

  • target_shares – Target class proportions of shape (J,) summing to 1.0.

  • lambdas – Optional sequence of non-negative penalty values (may include 0.0 and float("inf")).

  • row_weights – Optional strictly positive row weights of shape (N,).

  • reference – Optional reference probability matrix R.

  • anchor – Optional ranking anchor matrix A.

  • ties – "weak" (default) or "stable".

  • loss – "kl" (default) or "euclidean".

  • tol – Solver convergence tolerance.

  • verbose – If True, print solver progress.

Returns:

ParetoResult containing sorted penalties, calibrated matrices, KL divergences, and rank-violation trajectories.

Raises:

CalibrationError – If lambdas is empty or contains invalid values.

rank_preserving_calibration.evaluate(calibrated: ArrayLike, probs: ArrayLike, target_shares: ArrayLike, *, row_weights: ArrayLike | None = None, reference: ArrayLike | None = None, anchor: ArrayLike | None = None, y: ArrayLike | None = None, tol: float = 1e-06) → EvaluationResult[source]

Audit any calibrated probability matrix against marginals, ranks, and labels.

Works on outputs from calibrate(), IPF, BISG, or any external calibrator.

Parameters:
  • calibrated – Calibrated probability matrix of shape (N, J) to audit.

  • probs – Original pre-calibration probability matrix of shape (N, J).

  • target_shares – Target class proportions of shape (J,) summing to 1.0.

  • row_weights – Optional positive row weights of shape (N,).

  • reference – Optional reference matrix for KL divergence (defaults to probs).

  • anchor – Optional anchor matrix for rank metrics (defaults to probs).

  • y – Optional integer class labels of shape (N,) in {0, ..., J-1} to compute multiclass Brier score and negative log-likelihood.

  • tol – Numerical slack for counting pairwise rank reversals.

Returns:

EvaluationResult with feasibility, divergence, rank, and optional proper-scoring diagnostics.

Raises:

CalibrationError – If any input array has invalid shape or values.

Temperature Scaling Helpers

rank_preserving_calibration.fit_temperature(probs: ArrayLike, y: ArrayLike, *, bounds: tuple[float, float] = (0.05, 20.0)) → float[source]

Fit a scalar temperature minimizing multiclass negative log-likelihood.

Use this on a source validation split to obtain reference = apply_temperature(probs_test, tau) while keeping anchor = probs_test in calibrate().

Parameters:
  • probs – Validation probability matrix of shape (N, J).

  • y – Integer class labels of shape (N,) in {0, ..., J - 1}.

  • bounds – Lower and upper search bounds (low, high) with 0 < low < high.

Returns:

Optimal scalar temperature tau > 0.

Raises:

CalibrationError – If probs, y, or bounds are invalid.

rank_preserving_calibration.apply_temperature(probs: ArrayLike, temperature: float) → np.ndarray[source]

Rescale predicted probabilities by a positive scalar temperature.

Computes softmax(log(probs) / temperature) row-wise. Temperatures greater than 1 soften overconfident predictions; values below 1 sharpen underconfident predictions.

Parameters:
  • probs – Input probability matrix of shape (N, J).

  • temperature – Strictly positive scalar temperature.

Returns:

Temperature-scaled probability matrix of shape (N, J).

Raises:

CalibrationError – If probs is invalid or temperature <= 0.

Result Types and Exceptions

class rank_preserving_calibration.CalibrationResult(probs: np.ndarray, converged: bool, kl_divergence: float, max_row_error: float, max_marginal_error: float, max_rank_violation: float, l1_rank_violation: float, rank_preservation_pct: float, iterations: int)[source]

Output of calibrate().

Variables:
  • probs (np.ndarray) – Calibrated probability matrix of shape (N, J).

  • converged (bool) – True when simplex and marginal tolerances are met.

  • kl_divergence (float) – Mean weighted KL divergence per unit from reference.

  • max_row_error (float) – Maximum absolute row-sum error |sum_j q_ij - 1|.

  • max_marginal_error (float) – Maximum absolute class-share error |sum_i (w_i / W) q_ij - target_shares_j|.

  • max_rank_violation (float) – Largest weak-order violation across all columns.

  • l1_rank_violation (float) – Total L1 weak-order hinge violation across columns.

  • rank_preservation_pct (float) – Percentage of strictly ordered anchor pairs whose weak ordering survives calibration.

  • iterations (int) – Solver iteration count.

probs: np.ndarray
converged: bool
kl_divergence: float
max_row_error: float
max_marginal_error: float
max_rank_violation: float
l1_rank_violation: float
rank_preservation_pct: float
iterations: int
class rank_preserving_calibration.DiagnosisResult(ipf_probs: np.ndarray, multipliers: np.ndarray, l1_shift: float, max_rank_violation: float, l1_rank_violation: float, rank_preservation_pct: float, n_reversed_pairs: int, worst_reversals: list[ReversalExample])[source]

Output of diagnose().

Variables:
  • ipf_probs (np.ndarray) – Unconstrained IPF probability matrix of shape (N, J).

  • multipliers (np.ndarray) – Positive IPF column multipliers normalized to unit geometric mean across positive-target classes.

  • l1_shift (float) – L1 distance between empirical and target class shares in [0, 2].

  • max_rank_violation (float) – Largest within-class reversal induced by IPF.

  • l1_rank_violation (float) – Total L1 weak-order hinge violation under IPF.

  • rank_preservation_pct (float) – Percentage of strictly ordered pairs kept by IPF.

  • n_reversed_pairs (int) – Count of strictly ordered pairs reversed by IPF.

  • worst_reversals (list[ReversalExample]) – Up to top_k largest reversed pairs.

ipf_probs: np.ndarray
multipliers: np.ndarray
l1_shift: float
max_rank_violation: float
l1_rank_violation: float
rank_preservation_pct: float
n_reversed_pairs: int
worst_reversals: list[ReversalExample]
class rank_preserving_calibration.ReversalExample(class_idx: int, higher_idx: int, lower_idx: int, p_higher: float, p_lower: float, q_higher: float, q_lower: float, gap: float)[source]

One within-class pair whose ordering IPF reverses.

Variables:
  • class_idx (int) – Zero-based class column index.

  • higher_idx (int) – Row index that started with the higher probability.

  • lower_idx (int) – Row index that started with the lower probability.

  • p_higher (float) – Initial probability of higher_idx for class_idx.

  • p_lower (float) – Initial probability of lower_idx for class_idx.

  • q_higher (float) – Calibrated probability of higher_idx after IPF.

  • q_lower (float) – Calibrated probability of lower_idx after IPF.

  • gap (float) – Magnitude of the reversal, q_lower - q_higher > 0.

class_idx: int
higher_idx: int
lower_idx: int
p_higher: float
p_lower: float
q_higher: float
q_lower: float
gap: float
class rank_preserving_calibration.ParetoResult(lambdas: list[float], probs: list[np.ndarray], kl_divergences: list[float], l1_rank_violations: list[float], max_rank_violations: list[float], rank_preservation_pcts: list[float])[source]

Output of pareto().

Variables:
  • lambdas (list[float]) – Sorted rank-penalty values swept (may include 0.0 and inf).

  • probs (list[np.ndarray]) – Calibrated probability matrix for each lambda.

  • kl_divergences (list[float]) – Mean weighted KL divergence for each solution.

  • l1_rank_violations (list[float]) – Total L1 weak-order violation for each solution.

  • max_rank_violations (list[float]) – Maximum weak-order violation for each solution.

  • rank_preservation_pcts (list[float]) – Pairwise rank preservation percentage for each solution.

lambdas: list[float]
probs: list[np.ndarray]
kl_divergences: list[float]
l1_rank_violations: list[float]
max_rank_violations: list[float]
rank_preservation_pcts: list[float]
class rank_preserving_calibration.EvaluationResult(max_row_error: float, max_marginal_error: float, kl_divergence: float, max_rank_violation: float, l1_rank_violation: float, rank_preservation_pct: float, brier: float | None, nll: float | None)[source]

Output of evaluate().

Variables:
  • max_row_error (float) – Maximum absolute row-sum error.

  • max_marginal_error (float) – Maximum absolute class-share error against target_shares.

  • kl_divergence (float) – Mean weighted KL divergence from reference.

  • max_rank_violation (float) – Largest weak-order violation against anchor.

  • l1_rank_violation (float) – Total L1 weak-order violation against anchor.

  • rank_preservation_pct (float) – Percentage of strictly ordered anchor pairs kept.

  • brier (float | None) – Weighted multiclass Brier score if labels y are given, else None.

  • nll (float | None) – Weighted multiclass negative log-likelihood if y is given, else None.

max_row_error: float
max_marginal_error: float
kl_divergence: float
max_rank_violation: float
l1_rank_violation: float
rank_preservation_pct: float
brier: float | None
nll: float | None
exception rank_preserving_calibration.CalibrationError[source]

Raised when inputs are invalid or a calibration solve fails.