Flexible Mondrian: Per-Group Coverage

This example demonstrates Flexible Mondrian conformal prediction, which provides coverage guarantees for arbitrary subgroups.

Use case: Ensure equal coverage across geographic regions, demographic groups, or any categorical variable.

Key Takeaways:

Setup and Data Generation

We simulate a scenario with 3 geographic regions where model performance varies by region.

Code
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

from conformalpy.classifier import ConformalClassifier
from conformalpy.evaluation import coverage_score
from conformalpy.nonconformity.classification import lac_nonconformity

# Generate classification data
np.random.seed(42)
X, y = make_classification(
    n_samples=3000,
    n_features=10,
    n_classes=2,
    n_informative=5,
    random_state=42,
)

# Create geographic regions with different difficulty levels
groups = np.random.choice(["North", "South", "West"], size=len(y), p=[0.4, 0.35, 0.25])

# Make 'West' region harder (flip some labels)
west_mask = groups == "West"
flip_prob = 0.2
flip_mask = np.random.rand(len(y)) < flip_prob
y[west_mask & flip_mask] = 1 - y[west_mask & flip_mask]

# Split data
X_train, X_temp, y_train, y_temp, g_train, g_temp = train_test_split(X, y, groups, test_size=0.4, random_state=42)
X_calib, X_test, y_calib, y_test, g_calib, g_test = train_test_split(
    X_temp, y_temp, g_temp, test_size=0.5, random_state=42
)

print(f"Train: {len(y_train)}, Calibration: {len(y_calib)}, Test: {len(y_test)}")
print(f"Regions in test: {np.unique(g_test)}")
Train: 1800, Calibration: 600, Test: 600
Regions in test: ['North' 'South' 'West']

Train Base Model

Fit a RandomForest classifier on training data.

Code
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
print(f"Model accuracy: {model.score(X_test, y_test):.1%}")
Model accuracy: 83.2%

Standard Conformal Prediction

First, let’s see coverage per region with standard (non-Mondrian) CP.

Code
cc_standard = ConformalClassifier(
    model=model,
    alpha=0.10,
    nonconformity_function=lac_nonconformity,
)

cc_standard.calibrate(X_calib, y_calib)  # No groups
pred_sets_standard = cc_standard.predict(X_test)

print("\n=== Standard Conformal (Single Threshold) ===")
print(f"Overall coverage: {coverage_score(pred_sets_standard, y_test):.1%}")
print(f"Global qhat: {cc_standard.qhat_:.4f}")

# Coverage per region
print("\nCoverage by region:")
for region in ["North", "South", "West"]:
    mask = g_test == region
    covered = [y_test[i] in pred_sets_standard[i] for i in np.where(mask)[0]]
    cov = np.mean(covered)
    print(f"  {region}: {cov:.1%} (n={np.sum(mask)})")

=== Standard Conformal (Single Threshold) ===
Overall coverage: 89.8%
Global qhat: 0.6100

Coverage by region:
  North: 94.9% (n=235)
  South: 93.0% (n=214)
  West: 77.5% (n=151)

Flexible Mondrian

Now calibrate with groups to get per-region coverage guarantees.

Code
cc_mondrian = ConformalClassifier(
    model=model,
    alpha=0.10,
    nonconformity_function=lac_nonconformity,
)

# Calibrate with groups
cc_mondrian.calibrate(X_calib, y_calib, groups=g_calib)

# Predict with groups
pred_sets_mondrian = cc_mondrian.predict(X_test, groups=g_test)

print("\n=== Flexible Mondrian (Per-Region Thresholds) ===")
print(f"Overall coverage: {coverage_score(pred_sets_mondrian, y_test):.1%}")
print(f"Per-group qhat: {cc_mondrian.qhat_per_group_}")

# Coverage per region
print("\nCoverage by region:")
for region in ["North", "South", "West"]:
    mask = g_test == region
    covered = [y_test[i] in pred_sets_mondrian[i] for i in np.where(mask)[0]]
    cov = np.mean(covered)
    print(f"  {region}: {cov:.1%} (n={np.sum(mask)})")

=== Flexible Mondrian (Per-Region Thresholds) ===
Overall coverage: 92.5%
Per-group qhat: {np.str_('North'): 0.5409302325581393, np.str_('South'): 0.6009239130434784, np.str_('West'): 0.8200000000000001}

Coverage by region:
  North: 91.9% (n=235)
  South: 93.0% (n=214)
  West: 92.7% (n=151)

Compare Coverage Distribution

Visualize the difference in coverage across regions.

Code
fig, axes = plt.subplots(1, 2, figsize=(12, 5))

regions = ["North", "South", "West"]
coverages_standard = []
coverages_mondrian = []
counts = []

for region in regions:
    mask = g_test == region
    counts.append(np.sum(mask))

    # Standard CP coverage
    covered_std = [y_test[i] in pred_sets_standard[i] for i in np.where(mask)[0]]
    coverages_standard.append(np.mean(covered_std))

    # Mondrian coverage
    covered_mon = [y_test[i] in pred_sets_mondrian[i] for i in np.where(mask)[0]]
    coverages_mondrian.append(np.mean(covered_mon))

x = np.arange(len(regions))
width = 0.35

# Coverage comparison
ax = axes[0]
bars1 = ax.bar(x - width / 2, coverages_standard, width, label="Standard CP", color="steelblue")
bars2 = ax.bar(x + width / 2, coverages_mondrian, width, label="Flexible Mondrian", color="coral")
ax.axhline(y=0.90, color="red", linestyle="--", linewidth=2, label="Target (90%)")
ax.set_ylabel("Coverage")
ax.set_xlabel("Region")
ax.set_title("Coverage by Region")
ax.set_xticks(x)
ax.set_xticklabels(regions)
ax.legend()
ax.set_ylim(0.8, 1.0)

# Add value labels
for bar, cov in zip(bars1, coverages_standard):
    ax.annotate(
        f"{cov:.1%}",
        xy=(bar.get_x() + bar.get_width() / 2, bar.get_height()),
        xytext=(0, 3),
        textcoords="offset points",
        ha="center",
        va="bottom",
        fontsize=9,
    )
for bar, cov in zip(bars2, coverages_mondrian):
    ax.annotate(
        f"{cov:.1%}",
        xy=(bar.get_x() + bar.get_width() / 2, bar.get_height()),
        xytext=(0, 3),
        textcoords="offset points",
        ha="center",
        va="bottom",
        fontsize=9,
    )

# Per-group qhat
ax2 = axes[1]
qhats = [cc_mondrian.qhat_per_group_[r] for r in regions]
bars = ax2.bar(regions, qhats, color=["#2ca02c", "#ff7f0e", "#d62728"])
ax2.axhline(
    y=cc_standard.qhat_, color="steelblue", linestyle="--", linewidth=2, label=f"Global qhat ({cc_standard.qhat_:.3f})"
)
ax2.set_ylabel("qhat (threshold)")
ax2.set_xlabel("Region")
ax2.set_title("Calibrated Thresholds by Region")
ax2.legend()

# Add value labels
for bar, qhat in zip(bars, qhats):
    ax2.annotate(
        f"{qhat:.3f}",
        xy=(bar.get_x() + bar.get_width() / 2, bar.get_height()),
        xytext=(0, 3),
        textcoords="offset points",
        ha="center",
        va="bottom",
        fontsize=10,
    )

plt.tight_layout()
plt.suptitle("Flexible Mondrian vs Standard Conformal Prediction", fontsize=14, y=1.02)
plt.show()

Summary

Flexible Mondrian ensures coverage guarantees are maintained within each group:

  • Standard CP: May under-cover difficult subgroups (West region)
  • Flexible Mondrian: Calibrates separate thresholds per group
  • Trade-off: Larger average set sizes in difficult groups

When to use Flexible Mondrian:

  • Fairness requirements across demographic groups
  • Different operating conditions (regions, time periods)
  • Known subpopulation heterogeneity
  • When per-group coverage is more important than overall efficiency