Metadata-Version: 2.4
Name: rank_preserving_calibration
Version: 1.0.0
Summary: Rank-preserving marginal calibration for multiclass probabilities via weak-order KL exponential-cone programming.
Keywords: calibration,multiclass,marginal-calibration,ipf,kl-divergence,isotonic,survey-statistics,mrp
Author: Gaurav Sood
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Dist: numpy>=2.1.0
Requires-Dist: scipy>=1.14.1
Requires-Dist: clarabel>=0.11.1
Requires-Python: >=3.13
Project-URL: Homepage, https://github.com/finite-sample/rank-preserving-calibration
Project-URL: Source, https://github.com/finite-sample/rank-preserving-calibration
Project-URL: Issues, https://github.com/finite-sample/rank-preserving-calibration/issues
Project-URL: Documentation, https://finite-sample.github.io/rank-preserving-calibration/
Description-Content-Type: text/markdown

# Rank-Preserving Marginal Calibration for Multiclass Probabilities

[![CI](https://github.com/finite-sample/rank-preserving-calibration/actions/workflows/ci.yml/badge.svg)](https://github.com/finite-sample/rank-preserving-calibration/actions/workflows/ci.yml)
[![PyPI version](https://img.shields.io/pypi/v/rank-preserving-calibration.svg)](https://pypi.org/project/rank-preserving-calibration/)
[![Documentation](https://img.shields.io/badge/docs-github.io-blue)](https://finite-sample.github.io/rank-preserving-calibration/)
[![Python versions](https://img.shields.io/pypi/pyversions/rank-preserving-calibration.svg)](https://pypi.org/project/rank-preserving-calibration/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/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](https://clarabel.org/), supporting both individual-level tables and weighted poststratification / survey cells (`row_weights`).

## Installation

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

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

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

```python
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](https://gsood.com/research/papers/multiclass-rank-calibration.pdf)).
