Quick Start Guide¶
This guide walks through the core workflow in rank_preserving_calibration:
diagnosing IPF rank reversals, calibrating with strict or soft KL constraints,
sweeping the Pareto frontier, weighting poststratification cells, and
decoupling temperature scaling from the ranking anchor.
1. Diagnose IPF Reversals First¶
Before adding rank constraints, check whether standard Iterative Proportional
Fitting (IPF) actually reverses within-class rankings on your table. 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([2.0, 1.0, 1.0, 1.0], size=150)
target_shares = np.array([0.15, 0.50, 0.20, 0.15])
diag = rpc.diagnose(probs, target_shares, top_k=3)
print(f"L1 shift: {diag.l1_shift:.3f}")
print(f"IPF rank preservation: {diag.rank_preservation_pct:.1f}%")
print(f"Worst IPF reversal: {diag.max_rank_violation:.3f}")
for ex in diag.worst_reversals:
print(
f" class {ex.class_idx}: row {ex.higher_idx} ({ex.p_higher:.3f} -> {ex.q_higher:.3f}) "
f"vs row {ex.lower_idx} ({ex.p_lower:.3f} -> {ex.q_lower:.3f})"
)
2. Calibrate with One Continuous Dial (rank_penalty)¶
calibrate() matches target_shares via an
exact weak-order KL exponential-cone program solved by Clarabel. The single
argument rank_penalty spans the entire family:
rank_penalty=None(default): strict weak-order preservation (zero reversals).rank_penalty=1.0(any positive float): soft weak-order KL calibration.rank_penalty=0.0: unconstrained IPF.
strict = rpc.calibrate(probs, target_shares)
soft = rpc.calibrate(probs, target_shares, rank_penalty=1.0)
ipf = rpc.calibrate(probs, target_shares, rank_penalty=0.0)
print(
f"Strict: KL={strict.kl_divergence:.4f}, max_viol={strict.max_rank_violation:.2e}"
)
print(f"Soft: KL={soft.kl_divergence:.4f}, max_viol={soft.max_rank_violation:.3f}")
print(f"IPF: KL={ipf.kl_divergence:.4f}, max_viol={ipf.max_rank_violation:.3f}")
3. Explore the Pareto Frontier¶
When you are unsure which rank_penalty to choose, sweep the full curve from
0.0 (IPF) to inf (strict weak-order KL) with
pareto():
frontier = rpc.pareto(probs, target_shares)
for lam, kl, viol, pct in zip(
frontier.lambdas,
frontier.kl_divergences,
frontier.max_rank_violations,
frontier.rank_preservation_pcts,
strict=True,
):
print(f"lam={lam:>5g} KL={kl:.4f} max_viol={viol:.4f} rank={pct:5.1f}%")
4. Weighted Poststratification and Survey Cells¶
In MRP and survey weighting, rows often represent demographic or surname cells
with population counts row_weights rather than individual respondents. Pass
row_weights directly; target_shares remain class 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,
)
assert weighted.converged
assert weighted.max_marginal_error < 1e-6
5. Decoupled Temperature Scaling (Temp + KL soft)¶
If your base classifier is overconfident and you have a source validation split
(probs_val, y_val), fit a scalar temperature first, pass the softened
probabilities as reference, and keep the original scores as anchor:
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,
)
report = rpc.evaluate(res.probs, probs_test, target_shares, y=y_test)
print(
f"Brier={report.brier:.3f}, NLL={report.nll:.3f}, "
f"Rank={report.rank_preservation_pct:.1f}%"
)
Next Steps¶
Read Mathematical Theory for the formal results behind KL vs. Euclidean calibration.
Run the executable examples.
Inspect the full API Reference reference.