Note
Go to the end to download the full example code.
Diagnosing and Controlling Rank Reversals Under Label Shift¶
A multiclass classifier trained where every digit is equally common is deployed
where digits 0, 1, and 2 are four times as common as digits 3 through 9, and
the target shares are known. Standard Iterative Proportional Fitting (IPF)
matches the target shares exactly but reverses hundreds of within-class
rankings. Weak-order KL calibration trades off KL divergence against rank
preservation continuously across rank_penalty.
Train a classifier and construct a shifted target population¶
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_digits
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import train_test_split
import rank_preserving_calibration as rpc
X, y = load_digits(return_X_y=True)
X_train_full, X_pool, y_train_full, y_pool = train_test_split(
X, y, test_size=0.5, stratify=y, random_state=0
)
X_train, X_val, y_train, y_val = train_test_split(
X_train_full, y_train_full, test_size=0.25, stratify=y_train_full, random_state=0
)
model = HistGradientBoostingClassifier(max_iter=80, random_state=0)
model.fit(X_train, y_train)
probs_val = model.predict_proba(X_val)
rng = np.random.default_rng(0)
counts = np.where(np.arange(10) <= 2, 50, 12)
deploy = np.concatenate(
[
rng.choice(np.flatnonzero(y_pool == k), n, replace=False)
for k, n in enumerate(counts)
]
)
X_test, y_test = X_pool[deploy], y_pool[deploy]
probs_test = model.predict_proba(X_test)
target_shares = counts / counts.sum()
Step 1: Diagnose IPF reversals before choosing a constraint¶
diag = rpc.diagnose(probs_test, target_shares, top_k=3)
print(
f"L1 shift={diag.l1_shift:.3f}, IPF kept {diag.rank_preservation_pct:.1f}% "
f"of pairs ({diag.n_reversed_pairs} reversed, "
f"max gap={diag.max_rank_violation:.3f})"
)
L1 shift=0.013, IPF kept 96.3% of pairs (10153 reversed, max gap=0.365)
Step 2: Compare IPF, soft KL, strict KL, and decoupled Temp + KL soft¶
tau = rpc.fit_temperature(probs_val, y_val)
probs_temp = rpc.apply_temperature(probs_test, tau)
methods = {
"Original": probs_test,
"IPF": rpc.calibrate(probs_test, target_shares, rank_penalty=0.0).probs,
"KL soft (lam=1)": rpc.calibrate(probs_test, target_shares, rank_penalty=1.0).probs,
"KL strict": rpc.calibrate(probs_test, target_shares).probs,
"Temp + KL soft": rpc.calibrate(
probs_test,
target_shares,
reference=probs_temp,
anchor=probs_test,
rank_penalty=1.0,
).probs,
}
print(f"\n{'Method':<18} {'Brier':>7} {'NLL':>7} {'Rank %':>8} {'MaxMargErr':>11}")
for name, Q in methods.items():
ev = rpc.evaluate(Q, probs_test, target_shares, y=y_test)
print(
f"{name:<18} {ev.brier:7.3f} {ev.nll:7.3f} "
f"{ev.rank_preservation_pct:8.1f} {ev.max_marginal_error:11.2e}"
)
Method Brier NLL Rank % MaxMargErr
Original 0.038 0.077 100.0 3.82e-03
IPF 0.032 0.068 96.3 1.51e-05
KL soft (lam=1) 0.031 0.066 96.6 2.04e-13
KL strict 0.028 0.062 93.7 1.89e-08
Temp + KL soft 0.032 0.069 93.7 1.36e-12
Step 3: Plot the lambda-Pareto frontier¶
frontier = rpc.pareto(
probs_test,
target_shares,
lambdas=[0.0, 0.25, 0.5, 1.0, 2.0, 5.0, float("inf")],
)
briers = [
rpc.evaluate(Q, probs_test, target_shares, y=y_test).brier for Q in frontier.probs
]
fig, axes = plt.subplots(1, 2, figsize=(9.5, 3.6))
axes[0].plot(frontier.rank_preservation_pcts, briers, marker="o", color="#1f4e79")
axes[0].set_xlabel("Weak-order rank preservation (%)")
axes[0].set_ylabel("Held-out Brier score")
axes[0].set_title("Accuracy vs. rank preservation")
digits = np.arange(10)
axes[1].bar(digits - 0.2, probs_test.mean(axis=0), width=0.4, label="Original")
axes[1].bar(
digits + 0.2,
methods["Temp + KL soft"].mean(axis=0),
width=0.4,
label="Temp + KL soft",
)
axes[1].scatter(digits, target_shares, color="black", zorder=3, label="Target share")
axes[1].set_xticks(digits)
axes[1].set_xlabel("Digit class")
axes[1].set_ylabel("Predicted class share")
axes[1].set_title("Exact marginal alignment")
axes[1].legend()
fig.tight_layout()
plt.show()

Total running time of the script: (0 minutes 6.128 seconds)