Outcome Distribution Analysis

This example demonstrates how to categorize and visualize conformal prediction outcomes using the outcomes module.

Conformal predictions are categorized into five outcomes:

Setup

Create synthetic data and train a conformal classifier.

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

from conformalpy.classifier import ConformalClassifier
from conformalpy.nonconformity.classification import lac_nonconformity
from conformalpy.outcomes import (
    categorize_outcomes,
    outcome_counts,
    outcome_proportions,
    outcome_summary,
    si_error_analysis,
    si_error_report,
    singleton_confusion_matrix,
    singleton_confusion_report,
)
from conformalpy.plots import plot_singleton_confusion_matrix

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

# Split: train / calibration / test
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 base model
model = LogisticRegression(random_state=42, max_iter=1000)
model.fit(X_train, y_train)

# Create and calibrate conformal classifier
conf_clf = ConformalClassifier(
    model=model,
    alpha=0.10,  # 90% confidence level
    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"Alpha: {conf_clf.alpha}")
Test samples: 400
Alpha: 0.1

Categorize Outcomes

Assign each prediction to one of the five outcome categories.

Code
outcomes = categorize_outcomes(prediction_sets, y_test)

print("Sample outcomes:", outcomes[:10])
print("Unique outcomes:", np.unique(outcomes))
Sample outcomes: ['TS1' 'SI' 'TS1' 'SC' 'TS1' 'SC' 'TS1' 'SC' 'TS1' 'SC']
Unique outcomes: ['SC' 'SI' 'TS0' 'TS1']

Outcome Counts and Proportions

Get counts and proportions for each outcome.

Code
counts = outcome_counts(prediction_sets, y_test)
props = outcome_proportions(prediction_sets, y_test)

print("\nOutcome Counts:")
for outcome, count in counts.items():
    print(f"  {outcome}: {count}")

print("\nOutcome Proportions:")
for outcome, prop in props.items():
    print(f"  {outcome}: {prop:.1%}")

Outcome Counts:
  SC: 210
  SI: 33
  TS0: 68
  TS1: 89
  Empty: 0

Outcome Proportions:
  SC: 52.5%
  SI: 8.2%
  TS0: 17.0%
  TS1: 22.2%
  Empty: 0.0%

Visualize Outcome Distribution

Create a pie chart of outcome proportions.

Code
# Colors matching the PDP module
colors = {
    "SC": "#2ecc71",  # Green
    "SI": "#e74c3c",  # Red
    "TS0": "#3498db",  # Blue
    "TS1": "#9b59b6",  # Purple
    "Empty": "#95a5a6",  # Gray
}

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

# Pie chart
labels = [k for k in props.keys() if props[k] > 0]
sizes = [props[k] for k in labels]
pie_colors = [colors[k] for k in labels]

ax1.pie(sizes, labels=labels, colors=pie_colors, autopct="%1.1f%%", startangle=90)
ax1.set_title("Outcome Distribution (α=0.10)")

# Bar chart
outcomes_order = ["SC", "SI", "TS0", "TS1", "Empty"]
bar_heights = [props[k] for k in outcomes_order]
bar_colors = [colors[k] for k in outcomes_order]

bars = ax2.bar(outcomes_order, bar_heights, color=bar_colors)
ax2.set_ylabel("Proportion")
ax2.set_xlabel("Outcome")
ax2.set_title("Outcome Distribution (α=0.10)")
ax2.set_ylim(0, 1)

# Add value labels
for bar, height in zip(bars, bar_heights):
    ax2.text(bar.get_x() + bar.get_width() / 2, height + 0.02, f"{height:.1%}", ha="center", va="bottom")

plt.tight_layout()
plt.show()

Comprehensive Summary

Get all outcome statistics in one call.

Code
summary = outcome_summary(prediction_sets, y_test)

print("Outcome Summary:")
print(f"  Total samples: {summary['n_samples']}")
print(f"  Confidence rate (SC+SI): {summary['confidence_rate']:.1%}")
print(f"  Uncertainty rate (TS0+TS1): {summary['uncertainty_rate']:.1%}")
print(f"  Accuracy when confident: {summary['accuracy_when_confident']:.1%}")
print(f"  Coverage: {summary['coverage']:.1%}")
Outcome Summary:
  Total samples: 400
  Confidence rate (SC+SI): 60.8%
  Uncertainty rate (TS0+TS1): 39.2%
  Accuracy when confident: 86.4%
  Coverage: 91.8%

Compare Different Alpha Values

See how outcomes change with different confidence levels.

Code
alpha_values = [0.05, 0.10, 0.15, 0.20]
results = []

for alpha in alpha_values:
    conf_clf.alpha = alpha
    conf_clf.calibrate(X_cal, y_cal)
    pred_sets = conf_clf.predict(X_test)
    props = outcome_proportions(pred_sets, y_test)
    props["alpha"] = alpha
    results.append(props)

# Plot
fig, ax = plt.subplots(figsize=(10, 6))

x = np.arange(len(alpha_values))
width = 0.15

for i, outcome in enumerate(["SC", "SI", "TS0", "TS1"]):
    heights = [r[outcome] for r in results]
    offset = (i - 1.5) * width
    ax.bar(x + offset, heights, width, label=outcome, color=colors[outcome])

ax.set_xlabel("Alpha (α)")
ax.set_ylabel("Proportion")
ax.set_title("Outcome Distribution by Confidence Level")
ax.set_xticks(x)
ax.set_xticklabels([f"α={a}" for a in alpha_values])
ax.legend()
ax.set_ylim(0, 1)

plt.tight_layout()
plt.show()

SI Error Analysis

Single Incorrect (SI) outcomes are the failure mode of conformal prediction: the model was confident but wrong. Understanding the breakdown helps identify which types of errors dominate.

Code
# Reset to α=0.10 for SI analysis
conf_clf.alpha = 0.10
conf_clf.calibrate(X_cal, y_cal)
prediction_sets = conf_clf.predict(X_test)

# Get SI error breakdown
si_result = si_error_analysis(prediction_sets, y_test, class_names={0: "negative", 1: "positive"})

print("\n" + "=" * 50)
print("SI Error Analysis")
print("=" * 50)
print(f"Total SI errors: {si_result['n_si']} ({si_result['si_rate']:.1%} of samples)")
print("\nBreakdown:")
print(f"  False positives (pred=1, true=0): {si_result['confusion']['false_positive']}")
print(f"  False negatives (pred=0, true=1): {si_result['confusion']['false_negative']}")

==================================================
SI Error Analysis
==================================================
Total SI errors: 33 (8.2% of samples)

Breakdown:
  False positives (pred=1, true=0): 13
  False negatives (pred=0, true=1): 20

SI Error Report

Generate a formatted text report similar to sklearn’s classification_report.

Code
print(si_error_report(prediction_sets, y_test, class_names={0: "negative", 1: "positive"}))
SI Error Analysis
=================
Total SI errors: 33 (8.25% of samples)

By predicted class:
  Predicted negative: 20 (60.61%)
  Predicted positive: 13 (39.39%)

Confusion breakdown:
  False negatives (pred=negative, true=positive): 20 (60.61%)
  False positives (pred=positive, true=negative): 13 (39.39%)

Visualize SI Error Breakdown

See which type of confident-but-wrong error is more common.

Code
if si_result["n_si"] > 0:
    fig, ax = plt.subplots(figsize=(8, 4))

    error_types = ["False Negative\n(pred=0, true=1)", "False Positive\n(pred=1, true=0)"]
    error_counts = [
        si_result["confusion"]["false_negative"],
        si_result["confusion"]["false_positive"],
    ]
    error_colors = ["#e74c3c", "#c0392b"]  # Different red shades

    bars = ax.bar(error_types, error_counts, color=error_colors, edgecolor="black")

    ax.set_ylabel("Count")
    ax.set_title("SI Error Breakdown: Confident but Wrong Predictions")

    # Add value labels
    for bar, count in zip(bars, error_counts):
        prop = count / si_result["n_si"] * 100
        ax.text(
            bar.get_x() + bar.get_width() / 2,
            bar.get_height() + 0.5,
            f"{count} ({prop:.0f}%)",
            ha="center",
            va="bottom",
        )

    plt.tight_layout()
    plt.show()
else:
    print("No SI errors to visualize.")

Singleton Confusion Matrix

The singleton confusion matrix provides a complete breakdown of all singleton (confident) predictions, including both SC (correct) and SI (incorrect). This answers: “When the model is confident, how is it performing?”

Code
cm_result = singleton_confusion_matrix(prediction_sets, y_test, class_names={0: "negative", 1: "positive"})

print("\n" + "=" * 50)
print("Singleton Confusion Matrix")
print("=" * 50)
print(f"Total singletons: {cm_result['n_singletons']}")
print(f"  SC (Correct): {cm_result['n_sc']}")
print(f"  SI (Incorrect): {cm_result['n_si']}")
print("\nConfusion matrix breakdown:")
print(f"  TN (true negative): {cm_result['counts']['TN']}")
print(f"  FP (false positive): {cm_result['counts']['FP']}")
print(f"  FN (false negative): {cm_result['counts']['FN']}")
print(f"  TP (true positive): {cm_result['counts']['TP']}")

==================================================
Singleton Confusion Matrix
==================================================
Total singletons: 243
  SC (Correct): 210
  SI (Incorrect): 33

Confusion matrix breakdown:
  TN (true negative): 190
  FP (false positive): 13
  FN (false negative): 20
  TP (true positive): 20

Singleton Confusion Report

Generate a formatted text report for singleton predictions.

Code
print(singleton_confusion_report(prediction_sets, y_test, class_names={0: "negative", 1: "positive"}))
Singleton Prediction Analysis
=============================
Total singletons: 243 (60.75% of samples)

Confusion Matrix (singleton predictions only):
                 pred=negative  pred=positive
  true=negative          190           13
  true=positive           20           20

SC (Correct):  210 (86.42% of singletons)
  - True negatives (TN): 190 (90.48% of SC)
  - True positives (TP):  20 (9.52% of SC)

SI (Incorrect): 33 (13.58% of singletons)
  - False negatives (FN): 20 (60.61% of SI) [COSTLY]
  - False positives (FP):  13 (39.39% of SI)

Visualize Singleton Confusion Matrix

Create a visual representation showing both the confusion matrix and the composition of SC vs SI outcomes.

Code
fig, axes = plot_singleton_confusion_matrix(
    prediction_sets, y_test, class_names={0: "negative", 1: "positive"}, title="Singleton Prediction Analysis (α=0.10)"
)

Singleton Metrics

Analyze the precision and composition metrics for singleton predictions.

Code
metrics = cm_result["metrics"]

print("\nSingleton Metrics:")
print(f"  Precision for negative predictions: {metrics['precision_class_0']:.1%}")
print(f"  Precision for positive predictions: {metrics['precision_class_1']:.1%}")

print("\nSC Composition (within correct predictions):")
sc_comp = metrics["sc_composition"]
print(f"  True Negatives: {sc_comp['TN_ratio']:.1%}")
print(f"  True Positives: {sc_comp['TP_ratio']:.1%}")

if cm_result["n_si"] > 0:
    print("\nSI Composition (within incorrect predictions):")
    si_comp = metrics["si_composition"]
    print(f"  False Negatives: {si_comp['FN_ratio']:.1%}")
    print(f"  False Positives: {si_comp['FP_ratio']:.1%}")

Singleton Metrics:
  Precision for negative predictions: 90.5%
  Precision for positive predictions: 60.6%

SC Composition (within correct predictions):
  True Negatives: 90.5%
  True Positives: 9.5%

SI Composition (within incorrect predictions):
  False Negatives: 60.6%
  False Positives: 39.4%

Interpretation

Key insights from outcome analysis:

  • High SC rate indicates the model is often confident and correct
  • High SI rate is concerning - the model is confidently wrong
  • High TS rate indicates uncertainty - good for identifying hard cases
  • As α increases, prediction sets shrink -> more SC/SI, less TS

For SI error analysis:

  • False negatives (predicted negative, true positive) may be costly if missing positive cases has serious consequences
  • False positives (predicted positive, true negative) may cause unnecessary interventions or lost opportunities
  • The breakdown helps prioritize which type of error to address

For singleton confusion matrix:

  • TN + TP = SC (all correct singletons)
  • FN + FP = SI (all incorrect singletons)
  • SC composition shows if confidence is balanced between classes
  • Precision metrics show reliability of each predicted class

For operational use:

  • SC samples can often be auto-decided
  • TS samples may need manual review
  • SI samples indicate model calibration issues