Rank-Preserving Marginal Calibration for Multiclass Probabilities

CI PyPI version Documentation Python versions License: MIT

Match predicted multiclass probabilities to known population class shares while diagnosing and controlling within-class rank reversals.

When an outcome is binary (\(J = 2\)), matching a known population share by an intercept shift on the log-odds scale preserves every unit’s rank. For three or more classes (\(J \ge 3\)), standard multinomial intercept correction—Iterative Proportional Fitting (IPF)—divides each row by an instance-specific normalizing denominator and can reverse within-class rankings.

rank-preserving-calibration implements exact and soft weak-order Kullback–Leibler (KL) calibration as a sparse exponential-cone program via Clarabel, supporting both individual-level tables and weighted poststratification / survey cells (row_weights).

Installation

pip install rank-preserving-calibration

Runtime dependencies are numpy, scipy, and clarabel on Python 3.13+.

Quick Start

Every workflow centers on five jobs: diagnose, calibrate, explore the Pareto frontier, decouple temperature scaling, and audit. Target marginals are always passed as class shares summing to 1.0 (if you have counts, pass counts / counts.sum()).

import numpy as np
import rank_preserving_calibration as rpc

rng = np.random.default_rng(42)
probs = rng.dirichlet(np.ones(4), size=200)
target_shares = np.array([0.45, 0.25, 0.20, 0.10])

# 1. Diagnose whether IPF reverses within-class ranks on your table
diag = rpc.diagnose(probs, target_shares)
print(
    f"IPF kept {diag.rank_preservation_pct:.1f}% of pairs "
    f"(worst reversal: {diag.max_rank_violation:.3f})"
)

# 2. Calibrate with one continuous dial: rank_penalty
strict = rpc.calibrate(probs, target_shares)  # strict weak-order KL
soft = rpc.calibrate(probs, target_shares, rank_penalty=1.0)  # soft KL (lambda=1)
ipf = rpc.calibrate(probs, target_shares, rank_penalty=0.0)  # unconstrained IPF

assert strict.converged and strict.max_rank_violation < 1e-6
assert soft.converged and soft.max_marginal_error < 1e-6

# 3. Sweep the full accuracy vs. rank-preservation frontier (0 -> inf)
frontier = rpc.pareto(probs, target_shares)

Weighted Poststratification and Survey Cells

When rows represent MRP poststratification cells, demographic strata, or surname groups with population counts cell_counts (or survey weights), pass row_weights. Target shares remain proportions summing to 1.0:

cell_counts = rng.integers(10, 500, size=len(probs)).astype(float)
weighted = rpc.calibrate(
    probs,
    target_shares,
    row_weights=cell_counts,
    rank_penalty=1.0,
)

Decoupled Temperature Scaling (Temp + KL soft)

When a base classifier is overconfident and a source validation split (probs_val, y_val) is available, temperature-scale the KL reference while anchoring ranks to the original scores:

tau = rpc.fit_temperature(probs_val, y_val)
res = rpc.calibrate(
    probs_test,
    target_shares,
    reference=rpc.apply_temperature(probs_test, tau),
    anchor=probs_test,
    rank_penalty=1.0,
)

# Audit against held-out labels
report = rpc.evaluate(res.probs, probs_test, target_shares, y=y_test)
print(
    f"Brier={report.brier:.3f}, NLL={report.nll:.3f}, Rank={report.rank_preservation_pct:.1f}%"
)

Public API

Function / Type

Purpose

diagnose(probs, target_shares, *, row_weights, top_k)

Run IPF and inspect shift magnitude, reversed pairs, and worst reversals

calibrate(probs, target_shares, *, rank_penalty, row_weights, reference, anchor, ties, loss)

Exact strict KL (None), soft KL (float), IPF (0.0), or Euclidean QP (loss="euclidean")

pareto(probs, target_shares, *, lambdas, ...)

Trace KL divergence vs. rank violation from \(\lambda = 0\) to \(\lambda = \infty\)

fit_temperature(probs, y) / apply_temperature(probs, temperature)

Fit and apply scalar temperature scaling for decoupled reference probabilities

evaluate(calibrated, probs, target_shares, *, row_weights, y)

Audit simplex feasibility, marginal error, KL divergence, rank violations, Brier, and NLL

Paper and Citation

Details, proofs, and empirical benchmarks are in the accompanying working paper (Rank-Preserving Marginal Calibration for Multiclass Probabilities, PDF).

Documentation

Development

Indices and tables