Rank-Preserving Marginal Calibration for Multiclass Probabilities
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).
Metadata
Release files for rank-preserving-calibration 1.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| rank_preserving_calibration-1.0.0.tar.gz | 20.9 kB | With provenance | Details for rank_preserving_calibration-1.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| rank_preserving_calibration-1.0.0-py3-none-any.whl | Python 3 | none | any | Details for rank_preserving_calibration-1.0.0-py3-none-any.whl |
Total release size: 44.1 kB
Release files / rank_preserving_calibration-1.0.0.tar.gz
| Download URL | rank_preserving_calibration-1.0.0.tar.gz |
|---|---|
| Size | 20.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ff54a55fd4fdd8ecb30d3cb06aab2697486732997ab65742f4988f96e241c7a6
|
|
BLAKE2b-256 checksum How to use checksums |
80900feacdc36c30cc1a6b8e8e0644dfe64c9d06f5db5a4bda92e6dad09f4839
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logRelease files / rank_preserving_calibration-1.0.0-py3-none-any.whl
| Download URL | rank_preserving_calibration-1.0.0-py3-none-any.whl |
|---|---|
| Size | 23.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
0a1095d423c0995167727cd6379aa0906bf43b265337d02dc06991b68dd17c29
|
|
BLAKE2b-256 checksum How to use checksums |
c5abb6e656bf7158d37542aca54b63aa698e89c330589efae4294cae175c3aa6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logSecurity for rank-preserving-calibration 1.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for rank_preserving_calibration-1.0.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.