Explaining Conformal Predictions with SHAP

This example demonstrates how to explain conformal predictions using SHAP values applied to conformal p-values, following Johansson et al. (2025).

The key insight: conformal p-values are computed independently per class and do not sum to 1, so SHAP explanations of p-values carry richer information than SHAP explanations of model probabilities.

Setup

Generate synthetic binary classification data with named features, train a pipeline, and calibrate a conformal classifier.

Code
import warnings

import matplotlib.pyplot as plt
import numpy as np
import shap
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

from conformalpy.classifier import ConformalClassifier
from conformalpy.explainability import (
    ConformalPValueFunction,
    derive_confidence_shap,
    derive_margin_shap,
)
from conformalpy.nonconformity.classification import lac_nonconformity

warnings.filterwarnings("ignore", message="X has feature names")

# Generate data with informative feature names
X, y = make_classification(
    n_samples=600,
    n_features=5,
    n_informative=3,
    n_redundant=1,
    n_clusters_per_class=1,
    random_state=42,
)
feature_names = ["income", "debt_ratio", "credit_age", "n_accounts", "noise"]

# Split into train / calibration / test
X_train_cal, X_test, y_train_cal, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
X_train, X_cal, y_train, y_cal = train_test_split(X_train_cal, y_train_cal, test_size=0.33, random_state=42)

# Train a simple pipeline
pipeline = make_pipeline(StandardScaler(), LogisticRegression(random_state=42))
pipeline.fit(X_train, y_train)

# Create and calibrate conformal classifier
conf_clf = ConformalClassifier(
    model=pipeline,
    nonconformity_function=lac_nonconformity,
)
conf_clf.calibrate(X_cal, y_cal)
array([1.70842272e-01, 2.04316254e-02, 1.10482361e-01, 2.21160895e-02,
       3.95870672e-01, 3.75244357e-01, 1.26506400e-01, 9.54592375e-01,
       7.73089174e-02, 2.18362111e-02, 9.53729114e-01, 1.32026049e-01,
       1.99781483e-02, 3.81937455e-02, 1.47762565e-01, 1.37418239e-01,
       3.01059646e-01, 4.75925126e-02, 5.07181554e-01, 1.36265768e-02,
       3.27079329e-04, 5.00264491e-03, 1.50641078e-02, 4.59744806e-02,
       1.37296795e-03, 1.44844366e-01, 9.79708619e-02, 2.02852859e-01,
       2.60670417e-02, 8.58956317e-01, 4.13081632e-02, 1.24741020e-01,
       1.08805352e-01, 2.22318093e-01, 9.97897172e-01, 1.59192583e-02,
       1.03513383e-01, 2.15283456e-01, 1.57808096e-01, 8.45973837e-01,
       4.42069728e-02, 5.48164791e-01, 2.47899422e-01, 8.78923396e-01,
       8.40938168e-02, 8.79957085e-01, 1.56843162e-04, 9.72353798e-03,
       3.46415139e-03, 3.89623245e-03, 9.88705803e-01, 6.91541393e-02,
       8.54133061e-01, 1.95755715e-01, 5.02923371e-03, 6.41747368e-02,
       1.77691143e-02, 9.04906867e-03, 2.49797947e-01, 2.46020692e-02,
       2.29224267e-02, 2.14845236e-03, 1.70744664e-02, 2.20059672e-01,
       2.27008489e-01, 7.33195599e-04, 2.53724390e-03, 2.85951831e-02,
       8.50444656e-05, 2.18558278e-01, 2.63026860e-01, 7.29365689e-04,
       6.88912723e-01, 3.97755840e-02, 4.69477930e-01, 9.85720356e-01,
       8.70912893e-02, 6.68739703e-02, 1.34865349e-02, 2.82211376e-04,
       3.69949138e-03, 8.42689761e-02, 4.86104306e-01, 6.73877527e-03,
       4.62055472e-02, 2.25253668e-02, 4.83021935e-01, 3.00784546e-03,
       1.23375328e-01, 4.85469106e-02, 5.29375471e-04, 1.09367401e-01,
       1.73346364e-02, 1.91983119e-01, 5.05431180e-02, 2.90790932e-01,
       2.86854027e-01, 8.34273484e-02, 1.35251179e-01, 2.16830584e-03,
       1.48955619e-02, 5.92695049e-02, 1.78971041e-02, 9.23890231e-01,
       1.27095362e-02, 1.22917388e-01, 6.95660858e-06, 1.01169331e-01,
       1.53982972e-03, 1.07459334e-02, 2.79428421e-01, 7.63909146e-03,
       8.88896171e-04, 1.92277079e-01, 3.96012269e-01, 2.06888004e-02,
       3.32458137e-02, 2.13971354e-01, 2.12216166e-02, 1.87323166e-02,
       2.51465354e-05, 3.47485035e-02, 1.72078523e-01, 2.92158672e-01,
       2.15619752e-01, 1.03928720e-02, 7.05997126e-01, 8.49620693e-01,
       8.58443753e-04, 1.25034268e-01, 1.60656506e-01, 1.32046309e-02,
       2.13816707e-01, 1.70979885e-02, 1.50245951e-02, 6.86651605e-02,
       1.07967854e-01, 1.92218524e-01, 3.42947747e-01, 4.88951133e-04,
       2.86343506e-01, 1.41110895e-01, 8.87700275e-01, 1.43700507e-02,
       2.88178301e-03, 8.63558807e-01, 1.52981826e-02, 6.08048260e-02,
       6.23702478e-03])

Compute SHAP Values for Conformal P-Values

Wrap the conformal pipeline and create a KernelExplainer.

Code
pv_func = ConformalPValueFunction(conf_clf, feature_names=feature_names)

# Use a small background set for speed
background = shap.kmeans(X_train, 30)
explainer = shap.KernelExplainer(pv_func, background)

# Explain a subset of test instances
n_explain = 20
X_explain = X_test[:n_explain]
y_explain = y_test[:n_explain]

# shap_values shape: (n_samples, n_features, n_outputs)
shap_values_3d = explainer.shap_values(X_explain)

# Extract per-class SHAP values: (n_samples, n_features)
shap_class0 = shap_values_3d[:, :, 0]
shap_class1 = shap_values_3d[:, :, 1]

P-Values Are Not Probabilities

The SHAP baselines (expected values) for conformal p-values do not sum to 1, confirming that these are genuinely conformal p-value explanations.

Code
p_values = conf_clf.predict_p_values(X_explain)

print(f"SHAP base value class 0: {explainer.expected_value[0]:.4f}")
print(f"SHAP base value class 1: {explainer.expected_value[1]:.4f}")
print(f"Sum of base values:      {sum(explainer.expected_value):.4f}")
print("  (would be 1.0 for probabilities)")
SHAP base value class 0: 0.2284
SHAP base value class 1: 0.3478
Sum of base values:      0.5762
  (would be 1.0 for probabilities)
Code
# SHAP values for different classes are NOT negations
mean_abs_class0 = np.mean(np.abs(shap_class0), axis=0)
mean_abs_class1 = np.mean(np.abs(shap_class1), axis=0)

fig, ax = plt.subplots(figsize=(8, 4))
x_pos = np.arange(len(feature_names))
width = 0.35
ax.bar(x_pos - width / 2, mean_abs_class0, width, label="Class 0 p-value")
ax.bar(x_pos + width / 2, mean_abs_class1, width, label="Class 1 p-value")
ax.set_xticks(x_pos)
ax.set_xticklabels(feature_names, rotation=15)
ax.set_ylabel("Mean |SHAP value|")
ax.set_title("Per-Class P-Value SHAP (not negations of each other)")
ax.legend()
plt.tight_layout()
plt.show()

Margin SHAP

Derive margin SHAP values: which features drive the gap between true-class and false-class p-value evidence.

Code
# For each sample, select SHAP values of the true and false class
shap_p_true = np.where(y_explain[:, None] == 1, shap_class1, shap_class0)
shap_p_false = np.where(y_explain[:, None] == 1, shap_class0, shap_class1)

margin_shap = derive_margin_shap(shap_p_true, shap_p_false)

# Compare with 2 * SHAP(p_true) — they differ for conformal p-values
double_p_true = 2 * shap_p_true
max_diff = np.max(np.abs(margin_shap - double_p_true))
print(f"Max |margin_SHAP - 2*p_true_SHAP|: {max_diff:.6f}")
print("  (would be 0.0 if p-values were probabilities)")
Max |margin_SHAP - 2*p_true_SHAP|: 0.384310
  (would be 0.0 if p-values were probabilities)
Code
# Visualize margin SHAP
mean_margin = np.mean(margin_shap, axis=0)
colors = ["#2ca02c" if v > 0 else "#d62728" for v in mean_margin]

fig, ax = plt.subplots(figsize=(8, 4))
ax.barh(feature_names, mean_margin, color=colors)
ax.set_xlabel("Mean Margin SHAP Value")
ax.set_title("Margin SHAP: Reliability Drivers (+) vs Risk Drivers (-)")
ax.axvline(0, color="black", linewidth=0.8)
plt.tight_layout()
plt.show()

Confidence SHAP

Which features affect prediction set size (confidence = 1 - p_second).

Code
# derive_confidence_shap expects a list of arrays, one per class
shap_per_class = [shap_class0, shap_class1]
confidence_shap = derive_confidence_shap(shap_per_class, p_values)

mean_conf = np.mean(confidence_shap, axis=0)

fig, ax = plt.subplots(figsize=(8, 4))
ax.barh(feature_names, mean_conf, color="#1f77b4")
ax.set_xlabel("Mean Confidence SHAP Value")
ax.set_title("Confidence SHAP: Effect on Prediction Set Size")
ax.axvline(0, color="black", linewidth=0.8)
plt.tight_layout()
plt.show()