Prediction Set Profile Plots

This example demonstrates how to visualize prediction set profiles across different features and categories using conformalpy.

These plots help understand how conformal prediction behavior varies across different subgroups of your data.

Setup

First, we create some mock data and train a simple conformal classifier.

Code
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.nonconformity.classification import lac_nonconformity
from conformalpy.plots import (
    plot_prediction_set_profiles_by_category,
    plot_prediction_set_profiles_by_feature,
    plot_prediction_set_profiles_split_by_true,
)

# Generate synthetic data
np.random.seed(42)
X, y = make_classification(
    n_samples=2000,
    n_features=10,
    n_informative=5,
    n_redundant=2,
    n_classes=2,
    weights=[0.7, 0.3],
    random_state=42,
)

# Add a categorical feature for demonstration
categories = np.random.choice(["Low", "Medium", "High", "Very High"], size=len(y))

# 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)
cat_train, cat_temp = train_test_split(categories, test_size=0.4, random_state=42)
cat_cal, cat_test = train_test_split(cat_temp, test_size=0.5, random_state=42)

# Train base model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# Create and calibrate conformal classifier
conf_clf = ConformalClassifier(
    model=model,
    alpha=0.1,
    nonconformity_function=lac_nonconformity,
)
conf_clf.calibrate(X_cal, y_cal)

# Get prediction sets
prediction_sets = conf_clf.predict(X_test)

print(f"Test samples: {len(y_test)}")
print(f"Coverage: {np.mean([y in ps for y, ps in zip(y_test, prediction_sets)]):.3f}")
Test samples: 400
Coverage: 0.905

Plot Profiles by Category

Visualize how prediction set types (correct, incorrect, two-class, empty) distribute across different categories.

Code
plot_prediction_set_profiles_by_category(
    cat_test,
    prediction_sets,
    y_test,
    title="Prediction Set Profiles by Risk Category",
    category_order="freq",  # Order by frequency
)
(<Figure size 1152x576 with 2 Axes>,
 <Axes: ylabel='Fraction per Type'>,
 <Axes: ylabel='Sample Count'>)

Plot Profiles by Category (Stacked)

The same plot with stacked bars for a different perspective.

Code
plot_prediction_set_profiles_by_category(
    cat_test,
    prediction_sets,
    y_test,
    title="Prediction Set Profiles by Risk Category (Stacked)",
    style="stacked",
)
(<Figure size 1152x576 with 2 Axes>,
 <Axes: ylabel='Fraction per Type'>,
 <Axes: ylabel='Sample Count'>)

Plot Profiles by Category (Count Mode)

Show absolute counts instead of fractions.

Code
plot_prediction_set_profiles_by_category(
    cat_test,
    prediction_sets,
    y_test,
    title="Prediction Set Counts by Risk Category",
    y_mode="count",
)
(<Figure size 1152x576 with 2 Axes>,
 <Axes: ylabel='Number of Samples'>,
 <Axes: ylabel='Sample Count'>)

Plot Profiles by Numeric Feature

Visualize how prediction behavior changes across a numeric feature’s range.

Code
# Use first feature as example
feature_values = X_test[:, 0]

plot_prediction_set_profiles_by_feature(
    feature_values,
    prediction_sets,
    y_test,
    bins=10,
    title="Prediction Set Profiles by Feature 0",
)
(<Figure size 1152x576 with 2 Axes>,
 <Axes: xlabel='Feature Value (binned)', ylabel='Fraction per Type'>,
 <Axes: ylabel='Sample Count'>)

Plot Profiles Split by True Label

Create separate subplots for each true class to see class-specific patterns.

Code
plot_prediction_set_profiles_split_by_true(
    cat_test,
    prediction_sets,
    y_test,
    label_names={0: "Class 0 (Majority)", 1: "Class 1 (Minority)"},
    title="Prediction Set Profiles by Category — Split by True Label",
    ncols=2,
)
(<Figure size 1612.8x691.2 with 4 Axes>,
 array([[<Axes: title={'center': 'True label = Class 0 (Majority)  (n=271)'}, ylabel='Fraction per Type'>,
         <Axes: title={'center': 'True label = Class 1 (Minority)  (n=129)'}, ylabel='Fraction per Type'>]],
       dtype=object))

Interpretation

These plots reveal important patterns:

  • One-Class Correct (green): Model made a confident, correct prediction
  • One-Class Incorrect (red): Model was confident but wrong
  • Two-Class Sets (blue): Model was uncertain, included both classes
  • No Sets (gray): Very rare at typical α levels

Key insights:

  1. Categories with more “red” need attention - the model is confidently wrong
  2. Categories with more “blue” indicate uncertainty - may need more training data
  3. The split-by-true-label view shows if issues are class-specific