Model Comparison with FCODs

This example demonstrates how to compare conformal prediction behavior between different models using Feature-Conditioned Outcome Distributions.

Comparing models helps identify:

Setup

Train two different models on the same data.

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

from conformalpy.classifier import ConformalClassifier
from conformalpy.fcod import (
    compute_fcod_with_ci,
    plot_model_comparison_fcod,
)
from conformalpy.nonconformity.classification import lac_nonconformity
from conformalpy.outcomes import outcome_proportions

# Generate synthetic data
np.random.seed(42)
X, y = make_classification(
    n_samples=3000,
    n_features=5,
    n_informative=3,
    n_classes=2,
    weights=[0.6, 0.4],
    flip_y=0.1,  # Add some noise
    random_state=42,
)

# Split data
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.4, random_state=42)
X_cal, X_test, y_cal, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)

Train Two Models

Compare Logistic Regression (simple) with Gradient Boosting (complex).

Code
# Model 1: Logistic Regression
model_lr = LogisticRegression(random_state=42, max_iter=1000)
model_lr.fit(X_train, y_train)

# Model 2: Gradient Boosting
model_gb = GradientBoostingClassifier(n_estimators=100, random_state=42)
model_gb.fit(X_train, y_train)

print(f"Logistic Regression accuracy: {model_lr.score(X_test, y_test):.3f}")
print(f"Gradient Boosting accuracy: {model_gb.score(X_test, y_test):.3f}")
Logistic Regression accuracy: 0.902
Gradient Boosting accuracy: 0.918

Create Conformal Classifiers

Calibrate both models with the same alpha.

Code
alpha = 0.10

conf_lr = ConformalClassifier(
    model=model_lr,
    alpha=alpha,
    nonconformity_function=lac_nonconformity,
)
conf_lr.calibrate(X_cal, y_cal)

conf_gb = ConformalClassifier(
    model=model_gb,
    alpha=alpha,
    nonconformity_function=lac_nonconformity,
)
conf_gb.calibrate(X_cal, y_cal)

# Get prediction sets
pred_sets_lr = conf_lr.predict(X_test)
pred_sets_gb = conf_gb.predict(X_test)

Compare Overall Outcome Distributions

Code
props_lr = outcome_proportions(pred_sets_lr, y_test)
props_gb = outcome_proportions(pred_sets_gb, y_test)

print("\nOutcome Proportions:")
print("-" * 50)
print(f"{'Outcome':<10} {'Logistic':>12} {'GradBoost':>12}")
print("-" * 50)
for outcome in ["SC", "SI", "TS0", "TS1", "Empty"]:
    print(f"{outcome:<10} {props_lr[outcome]:>12.1%} {props_gb[outcome]:>12.1%}")

Outcome Proportions:
--------------------------------------------------
Outcome        Logistic    GradBoost
--------------------------------------------------
SC                88.8%        91.8%
SI                 9.3%         8.0%
TS0                1.3%         0.2%
TS1                0.5%         0.0%
Empty              0.0%         0.0%

Compare FCODs for a Single Feature

See how the two models differ across feature values.

Code
feature_idx = 0
feature_name = "Feature 0"
feature_values = X_test[:, feature_idx]

# Compute FCODs with CI
fcod_lr = compute_fcod_with_ci(feature_values, pred_sets_lr, y_test, n_bootstrap=100, n_grid=30)
fcod_lr["feature_name"] = feature_name

fcod_gb = compute_fcod_with_ci(feature_values, pred_sets_gb, y_test, n_bootstrap=100, n_grid=30)
fcod_gb["feature_name"] = feature_name

Plot SC Comparison

Compare where each model is confident and correct.

Code
fig, ax = plt.subplots(figsize=(10, 6))
plot_model_comparison_fcod(
    {"Logistic Regression": fcod_lr, "Gradient Boosting": fcod_gb},
    outcome="SC",
    ax=ax,
    show_ci=True,
    title="Model Comparison: Single Correct (SC)",
    xlabel=feature_name,
)
plt.show()

Plot SI Comparison

Compare where each model is confidently wrong.

Code
fig, ax = plt.subplots(figsize=(10, 6))
plot_model_comparison_fcod(
    {"Logistic Regression": fcod_lr, "Gradient Boosting": fcod_gb},
    outcome="SI",
    ax=ax,
    show_ci=True,
    title="Model Comparison: Single Incorrect (SI)",
    xlabel=feature_name,
)
plt.show()

Compare All Outcomes Side-by-Side

Full comparison across all outcome types.

Code
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
outcomes = ["SC", "SI", "TS0", "TS1"]
titles = [
    "Single Correct (Confident & Right)",
    "Single Incorrect (Confident & Wrong)",
    "Two-Set, True=0 (Uncertain)",
    "Two-Set, True=1 (Uncertain)",
]

for ax, outcome, title in zip(axes.flatten(), outcomes, titles):
    plot_model_comparison_fcod(
        {"Logistic Regression": fcod_lr, "Gradient Boosting": fcod_gb},
        outcome=outcome,
        ax=ax,
        show_ci=True,
        title=title,
        xlabel=feature_name,
    )

plt.tight_layout()
plt.show()

Compute Uncertainty Difference

Find regions where models disagree on uncertainty.

Code
ts_lr = fcod_lr["TS0"] + fcod_lr["TS1"]
ts_gb = fcod_gb["TS0"] + fcod_gb["TS1"]
grid = fcod_lr["grid"]

fig, ax = plt.subplots(figsize=(10, 5))

ax.plot(grid, ts_lr, label="Logistic Regression", linewidth=2)
ax.plot(grid, ts_gb, label="Gradient Boosting", linewidth=2)
ax.fill_between(grid, ts_lr, ts_gb, alpha=0.3, label="Difference")

ax.set_xlabel(feature_name)
ax.set_ylabel("Uncertainty Rate (TS0 + TS1)")
ax.set_title("Model Uncertainty Comparison")
ax.legend()
ax.grid(True, alpha=0.3)

plt.show()

# Find max disagreement point
diff = np.abs(ts_lr - ts_gb)
max_diff_idx = np.argmax(diff)
print(f"\nMax disagreement at {feature_name} = {grid[max_diff_idx]:.2f}")
print(f"  LR uncertainty: {ts_lr[max_diff_idx]:.1%}")
print(f"  GB uncertainty: {ts_gb[max_diff_idx]:.1%}")


Max disagreement at Feature 0 = -2.43
  LR uncertainty: 12.0%
  GB uncertainty: 0.0%

Interpretation

Key insights from model comparison:

  • Higher SC: More confident and correct predictions
  • Higher SI: More concerning — model is confidently wrong
  • Higher TS: More cautious — hedges with both classes

In this example:

  • Gradient Boosting typically has higher SC (more confident)
  • Logistic Regression may be more cautious in some regions
  • The “best” model depends on the cost of different error types

Recommendations:

  • If SI cost is high -> prefer more cautious model
  • If automation rate matters -> prefer more confident model
  • Consider ensemble approaches in high-disagreement regions