Feature-Conditioned Outcome Distributions

This example demonstrates how to create Feature-Conditioned Outcome Distributions (FCODs) showing how outcome proportions vary across feature values.

Unlike traditional Partial Dependence Plots (Friedman 2001) that show expected predictions, FCODs show the conditional empirical distribution of each conformal outcome (SC, SI, TS0, TS1) as a function of feature values, with bootstrap confidence intervals.

The smoothed FCOD computation ensures that outcome proportions sum to 1.0 at every grid point, making stacked area plots interpretable.

Setup

Create synthetic data with a clear feature-outcome relationship.

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

from conformalpy.classifier import ConformalClassifier
from conformalpy.fcod import (
    compute_fcod,
    compute_fcod_with_ci,
    compute_multi_feature_fcod,
    merge_uncertain_outcomes,
    plot_fcod,
    plot_multi_feature_fcod,
    plot_stacked_bars_by_class,
    plot_stacked_fcod,
)
from conformalpy.nonconformity.classification import lac_nonconformity

# 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],
    random_state=42,
)
feature_names = ["Feature_A", "Feature_B", "Feature_C", "Feature_D", "Feature_E"]

# 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 model
model = GradientBoostingClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# Conformal classifier
conf_clf = ConformalClassifier(
    model=model,
    alpha=0.10,
    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"Base model accuracy: {model.score(X_test, y_test):.3f}")
Test samples: 600
Base model accuracy: 0.952

Basic FCOD Computation

Compute how outcomes vary with a single feature.

Code
feature_idx = 0
feature_values = X_test[:, feature_idx]

fcod = compute_fcod(feature_values, prediction_sets, y_test, n_grid=30, method="binned")

print(f"Grid shape: {fcod['grid'].shape}")
print(f"SC range: [{fcod['SC'].min():.2f}, {fcod['SC'].max():.2f}]")
Grid shape: (30,)
SC range: [0.00, 1.00]

Plot FCOD with Confidence Intervals

Bootstrap confidence intervals show uncertainty in the estimates.

Code
fcod_ci = compute_fcod_with_ci(
    feature_values,
    prediction_sets,
    y_test,
    n_bootstrap=100,
    n_grid=30,
    confidence_level=0.95,
)

fig, ax = plt.subplots(figsize=(10, 6))
plot_fcod(
    fcod_ci,
    ax=ax,
    show_ci=True,
    xlabel=feature_names[feature_idx],
    title=f"Outcome FCOD: {feature_names[feature_idx]}",
)
plt.show()

Stacked Area Plot

Show how the full outcome distribution changes across the feature range.

Code
fig, ax = plt.subplots(figsize=(10, 5))
plot_stacked_fcod(
    fcod_ci,
    ax=ax,
    xlabel=feature_names[feature_idx],
    title=f"Outcome Distribution: {feature_names[feature_idx]}",
)
plt.show()

Multi-Feature FCODs

Compute and plot FCODs for multiple features at once.

Code
# Compute FCODs for all features
fcods = compute_multi_feature_fcod(
    X_test,
    feature_names,
    prediction_sets,
    y_test,
    n_grid=25,
    method="smoothed",
)

# Plot grid
fig = plot_multi_feature_fcod(
    fcods,
    outcomes=["SC", "SI", "TS0", "TS1"],
    n_cols=3,
    show_ci=False,  # No CI for quick visualization
    figsize_per_plot=(4, 3),
)
plt.suptitle("Outcome FCODs for All Features", y=1.02)
plt.show()

Merging Binary Uncertain Outcomes

In binary classification TS0 and TS1 split the two-set outcome by true label. At decision time the true label is unknown, so this split has no operational value. merge_uncertain_outcomes collapses them into a single TS key, simplifying downstream plots and analysis.

Code
from conformalpy.fcod import merge_uncertain_outcomes

fcod_merged = merge_uncertain_outcomes(fcod_ci)

print("Keys before merge:", [k for k in fcod_ci if k not in ("grid", "n_samples", "feature_name", "method")])
print("Keys after merge: ", [k for k in fcod_merged if k not in ("grid", "n_samples", "feature_name", "method")])
Keys before merge: ['n_bootstrap', 'confidence_level', 'SC', 'SC_lower', 'SC_upper', 'SC_std', 'SI', 'SI_lower', 'SI_upper', 'SI_std', 'TS0', 'TS0_lower', 'TS0_upper', 'TS0_std', 'TS1', 'TS1_lower', 'TS1_upper', 'TS1_std', 'Empty', 'Empty_lower', 'Empty_upper', 'Empty_std']
Keys after merge:  ['n_bootstrap', 'confidence_level', 'SC', 'SC_lower', 'SC_upper', 'SC_std', 'SI', 'SI_lower', 'SI_upper', 'SI_std', 'TS0_std', 'TS1_std', 'Empty', 'Empty_lower', 'Empty_upper', 'Empty_std', 'TS', 'TS_lower', 'TS_upper']

The merged result works directly with all plot functions:

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

plot_fcod(
    fcod_merged,
    ax=axes[0],
    xlabel=feature_names[feature_idx],
    title="Line plot — merged TS",
)
plot_stacked_fcod(
    fcod_merged,
    ax=axes[1],
    xlabel=feature_names[feature_idx],
    title="Stacked area — merged TS",
)
plt.tight_layout()
plt.show()

Comparing Outcomes

Focus on SC (confident correct) vs TS (uncertain) to identify feature regions where the model is reliable vs uncertain.

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

# Plot SC (confidence)
ax1 = axes[0]
for name, fcod in fcods.items():
    ax1.plot(fcod["grid"], fcod["SC"], label=name, linewidth=2)
ax1.set_xlabel("Feature Value (standardized)")
ax1.set_ylabel("SC Proportion")
ax1.set_title("Where is the model confident and correct?")
ax1.legend()
ax1.grid(True, alpha=0.3)

# Plot TS (uncertainty) — use merge_uncertain_outcomes to avoid summing manually
ax2 = axes[1]
for name, fcod in fcods.items():
    merged = merge_uncertain_outcomes(fcod)
    ax2.plot(merged["grid"], merged["TS"], label=name, linewidth=2)
ax2.set_xlabel("Feature Value (standardized)")
ax2.set_ylabel("TS Proportion")
ax2.set_title("Where is the model uncertain?")
ax2.legend()
ax2.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

Feature Importance via FCOD Variance

Features with high FCOD variance are more influential on outcomes.

Code
variances = {}
for name, fcod in fcods.items():
    merged = merge_uncertain_outcomes(fcod)
    variances[name] = {
        "SC_var": np.var(merged["SC"]),
        "TS_var": np.var(merged["TS"]),
    }

print("Feature Importance (FCOD Variance):")
print("-" * 40)
for name, var in sorted(variances.items(), key=lambda x: x[1]["SC_var"], reverse=True):
    print(f"{name}: SC var={var['SC_var']:.4f}, TS var={var['TS_var']:.4f}")
Feature Importance (FCOD Variance):
----------------------------------------
Feature_A: SC var=0.0311, TS var=0.0000
Feature_C: SC var=0.0120, TS var=0.0000
Feature_E: SC var=0.0106, TS var=0.0015
Feature_D: SC var=0.0096, TS var=0.0000
Feature_B: SC var=0.0075, TS var=0.0000

Grid Trimming with Percentile Range

Feature extremes often have sparse data, leading to noisy estimates. Use percentile_range to focus on the data-rich region.

Code
from conformalpy.fcod import compute_fcod_smoothed

# Full range (default)
fcod_full = compute_fcod_smoothed(feature_values, prediction_sets, y_test, n_grid=50)

# Trimmed to 5th-95th percentile
fcod_trimmed = compute_fcod_smoothed(feature_values, prediction_sets, y_test, n_grid=50, percentile_range=(5, 95))

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

# Full range plot
ax1 = axes[0]
plot_stacked_fcod(fcod_full, ax=ax1, xlabel=feature_names[feature_idx])
ax1.set_title(f"Full Range: {feature_names[feature_idx]}")

# Trimmed plot
ax2 = axes[1]
plot_stacked_fcod(fcod_trimmed, ax=ax2, xlabel=feature_names[feature_idx])
ax2.set_title(f"5th-95th Percentile: {feature_names[feature_idx]}")

plt.tight_layout()
plt.show()

print(f"Full range: [{fcod_full['grid'].min():.2f}, {fcod_full['grid'].max():.2f}]")
print(f"Trimmed range: [{fcod_trimmed['grid'].min():.2f}, {fcod_trimmed['grid'].max():.2f}]")

Full range: [-3.90, 4.78]
Trimmed range: [-2.32, 1.99]

Data Density Visualization

FCODs can be misleading in regions with sparse data. Adding density visualization helps readers identify unreliable regions.

Two options are available:

  • Histogram: Marginal histogram below the FCOD showing data distribution
  • Rug plot: Vertical marks on the x-axis showing individual observations
Code
# Histogram density (default)
fig_main, fig_density = plot_fcod(
    fcod_ci,
    show_density=True,
    density_type="histogram",
    feature_values=feature_values,
    xlabel=feature_names[feature_idx],
    title=f"FCOD with Density Histogram: {feature_names[feature_idx]}",
)
plt.tight_layout()
plt.show()

# Rug plot density
fig, ax = plt.subplots(figsize=(10, 6))
plot_fcod(
    fcod_ci,
    ax=ax,
    show_density=True,
    density_type="rug",
    feature_values=feature_values,
    xlabel=feature_names[feature_idx],
    title=f"FCOD with Rug Plot: {feature_names[feature_idx]}",
)
plt.show()

# Stacked area with density
fig_main, fig_density = plot_stacked_fcod(
    fcod_ci,
    show_density=True,
    density_type="histogram",
    feature_values=feature_values,
    xlabel=feature_names[feature_idx],
    title=f"Stacked FCOD with Density: {feature_names[feature_idx]}",
)
plt.tight_layout()
plt.show()

Multiclass FCOD

For multiclass classification (K>2), the outcome categories change:

  • SC and SI remain the same (singleton correct/incorrect)
  • MC (Multi-set Covered) replaces TS0/TS1: multi-set containing the true label
  • MU (Multi-set Uncovered): multi-set NOT containing the true label

This generalizes naturally because in binary classification, a two-set always covers both classes, making MU impossible.

Code
from conformalpy.fcod import compute_fcod_smoothed as compute_fcod_smoothed_fn

np.random.seed(42)
X_mc, y_mc = make_classification(
    n_samples=3000,
    n_features=5,
    n_informative=3,
    n_classes=4,
    n_clusters_per_class=1,
    weights=[0.3, 0.3, 0.2, 0.2],
    random_state=42,
)
feature_names_mc = ["Feature_A", "Feature_B", "Feature_C", "Feature_D", "Feature_E"]

X_train_mc, X_temp_mc, y_train_mc, y_temp_mc = train_test_split(X_mc, y_mc, test_size=0.4, random_state=42)
X_cal_mc, X_test_mc, y_cal_mc, y_test_mc = train_test_split(X_temp_mc, y_temp_mc, test_size=0.5, random_state=42)

model_mc = GradientBoostingClassifier(n_estimators=100, random_state=42)
model_mc.fit(X_train_mc, y_train_mc)

conf_clf_mc = ConformalClassifier(
    model=model_mc,
    alpha=0.10,
    nonconformity_function=lac_nonconformity,
)
conf_clf_mc.calibrate(X_cal_mc, y_cal_mc)
prediction_sets_mc = conf_clf_mc.predict(X_test_mc)

# Compute multiclass FCOD (uses MC/MU instead of TS0/TS1)
feature_idx_mc = 0
feature_values_mc = X_test_mc[:, feature_idx_mc]
fcod_mc = compute_fcod_smoothed_fn(feature_values_mc, prediction_sets_mc, y_test_mc, n_grid=50, n_classes=4)

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

# Line plot
plot_fcod(
    fcod_mc,
    ax=axes[0],
    xlabel=feature_names_mc[feature_idx_mc],
    title=f"Multiclass FCOD: {feature_names_mc[feature_idx_mc]}",
)

# Stacked area plot
plot_stacked_fcod(
    fcod_mc,
    ax=axes[1],
    xlabel=feature_names_mc[feature_idx_mc],
    title=f"Multiclass Outcome Distribution: {feature_names_mc[feature_idx_mc]}",
)

plt.tight_layout()
plt.show()

print("Multiclass FCOD outcome keys:", [k for k in fcod_mc if k not in ("grid", "n_samples", "feature_name", "method")])

Multiclass FCOD outcome keys: ['SC', 'SI', 'MC', 'MU', 'Empty']

Per-Class Stacked Bars

plot_stacked_bars_by_class displays one full-width stacked-bar panel per class with a shared feature histogram at the bottom. This layout is cleaner than side-by-side columns when the feature grid has many points.

Code
from conformalpy.fcod import compute_fcod_smoothed, plot_stacked_bars_by_class

# Compute one FCOD per class for Feature_A
feature_idx = 0
fcod_by_class = {}
feature_values_by_class = {}

for cls in [0, 1]:
    mask = y_test == cls
    fcod_by_class[cls] = merge_uncertain_outcomes(
        compute_fcod_smoothed(
            X_test[mask, feature_idx],
            [prediction_sets[i] for i in np.where(mask)[0]],
            y_test[mask],
            n_grid=40,
        )
    )
    feature_values_by_class[cls] = X_test[mask, feature_idx]

fig = plot_stacked_bars_by_class(
    fcod_by_class=fcod_by_class,
    feature_values_by_class=feature_values_by_class,
    class_names={0: "Class 0", 1: "Class 1"},
    xlabel=feature_names[feature_idx],
    title=f"Outcome distribution by class — {feature_names[feature_idx]}",
    alpha=0.10,
)
plt.show()

Interpretation

Key insights from outcome FCODs:

  • Flat SC curve: Model confidence is stable across feature range
  • Rising SC curve: Model becomes more reliable at higher values
  • High TS region (binary) / High MC region (multiclass): Feature range where the model is uncertain
  • SI spikes: Dangerous regions where model is confidently wrong
  • MU spikes (multiclass): Regions with multi-set coverage failures
  • Low density regions: FCOD estimates may be unreliable

Operational implications:

  • Identify feature ranges for automatic vs manual decisions
  • Detect regions needing more training data
  • Compare model behavior across features
  • Use density visualization to avoid over-interpreting sparse regions

References

Friedman, Jerome H. 2001. “Greedy Function Approximation: A Gradient Boosting Machine.” The Annals of Statistics 29 (5): 1189–232. https://doi.org/10.1214/aos/1013203451.