Deep Learning Conformal Prediction

This example demonstrates how to use conformal prediction with PyTorch and Keras deep learning models.

conformalpy provides wrapper classes that adapt deep learning models to the sklearn-like interface expected by ConformalClassifier and ConformalRegressor.

Note: PyTorch and Keras are optional dependencies. Install them separately: pip install torch or pip install keras tensorflow. The core conformal prediction functionality works with any sklearn-compatible model.

Overview

Deep learning models from PyTorch or Keras can be used with conformal prediction through simple wrappers:

  • TorchClassifierWrapper / TorchRegressorWrapper for PyTorch
  • KerasClassifierWrapper / KerasRegressorWrapper for Keras

These wrappers handle:

  • Conversion between numpy arrays and framework tensors
  • Batched inference for large datasets
  • Output activation detection and normalization
Code
import matplotlib.pyplot as plt
import numpy as np

from conformalpy.deep_learning import is_keras_available, is_torch_available

print(f"PyTorch available: {is_torch_available()}")
print(f"Keras available: {is_keras_available()}")

Simulated Example

Since PyTorch and Keras are optional dependencies, we’ll demonstrate the workflow with a simulated example. The code structure is the same for real deep learning models.

Code
from sklearn.datasets import make_classification
from sklearn.neural_network import MLPClassifier

from conformalpy.classifier import ConformalClassifier
from conformalpy.nonconformity.classification import lac_nonconformity

# Generate synthetic data
X, y = make_classification(
    n_samples=500,
    n_features=20,
    n_classes=3,
    n_informative=10,
    random_state=42,
)

# Split data
X_train, X_calib, X_test = X[:300], X[300:400], X[400:]
y_train, y_calib, y_test = y[:300], y[300:400], y[400:]

# Train a neural network classifier (sklearn MLP as stand-in)
model = MLPClassifier(
    hidden_layer_sizes=(64, 32),
    max_iter=500,
    random_state=42,
)
model.fit(X_train, y_train)

Conformal Prediction with Neural Networks

Once trained, any model with predict_proba method works directly with conformal prediction.

Code
cc = ConformalClassifier(
    model=model,
    alpha=0.1,
    nonconformity_function=lac_nonconformity,
)

cc.calibrate(X_calib, y_calib)
pred_sets = cc.predict(X_test)

# Evaluate coverage
covered = [y_test[i] in pred_sets[i] for i in range(len(y_test))]
coverage = np.mean(covered)
avg_size = np.mean([len(s) for s in pred_sets])

print(f"Coverage: {coverage:.1%} (target: 90%)")
print(f"Average set size: {avg_size:.2f}")

Visualize Prediction Sets

Code
fig, axes = plt.subplots(1, 2, figsize=(10, 4))

# Distribution of set sizes
sizes = [len(s) for s in pred_sets]
axes[0].hist(sizes, bins=[0.5, 1.5, 2.5, 3.5], rwidth=0.8, color="steelblue")
axes[0].set_xlabel("Prediction Set Size")
axes[0].set_ylabel("Count")
axes[0].set_title("Distribution of Set Sizes")
axes[0].set_xticks([1, 2, 3])

# Coverage by class
class_coverage = []
for c in range(3):
    mask = y_test == c
    class_cov = np.mean([y_test[i] in pred_sets[i] for i in range(len(y_test)) if mask[i]])
    class_coverage.append(class_cov)

axes[1].bar(range(3), class_coverage, color=["#2ecc71", "#e74c3c", "#3498db"])
axes[1].axhline(y=0.9, color="black", linestyle="--", label="Target (90%)")
axes[1].set_xlabel("Class")
axes[1].set_ylabel("Coverage")
axes[1].set_title("Per-Class Coverage")
axes[1].set_ylim(0, 1.1)
axes[1].legend()

plt.tight_layout()
plt.show()

PyTorch Wrapper Usage

For PyTorch models, use TorchClassifierWrapper:

import torch
import torch.nn as nn
from conformalpy.deep_learning import TorchClassifierWrapper
from conformalpy.classifier import ConformalClassifier

# Define and train your PyTorch model
class Classifier(nn.Module):
    def __init__(self, n_features, n_classes):
        super().__init__()
        self.fc1 = nn.Linear(n_features, 64)
        self.fc2 = nn.Linear(64, n_classes)

    def forward(self, x):
        x = torch.relu(self.fc1(x))
        return self.fc2(x)

pytorch_model = Classifier(20, 3)
# ... train the model ...

# Wrap for conformal prediction
wrapped = TorchClassifierWrapper(
    pytorch_model,
    output_activation="softmax",  # Apply softmax to outputs
    device="cuda",  # Use GPU if available
    batch_size=256,
)

# Use with ConformalClassifier
cc = ConformalClassifier(model=wrapped, alpha=0.1)
cc.calibrate(X_calib, y_calib)
pred_sets = cc.predict(X_test)

Keras Wrapper Usage

For Keras/TensorFlow models, use KerasClassifierWrapper:

from keras.models import Sequential
from keras.layers import Dense
from conformalpy.deep_learning import KerasClassifierWrapper
from conformalpy.classifier import ConformalClassifier

# Build and train your Keras model
keras_model = Sequential([
    Dense(64, activation='relu', input_shape=(20,)),
    Dense(32, activation='relu'),
    Dense(3, activation='softmax'),
])
keras_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
# keras_model.fit(X_train, y_train, epochs=50)

# Wrap for conformal prediction
wrapped = KerasClassifierWrapper(
    keras_model,
    batch_size=256,
    output_activation="auto",  # Auto-detect from final layer
)

# Use with ConformalClassifier
cc = ConformalClassifier(model=wrapped, alpha=0.1)
cc.calibrate(X_calib, y_calib)
pred_sets = cc.predict(X_test)

Regression with Deep Learning

For regression tasks, use TorchRegressorWrapper or KerasRegressorWrapper:

from conformalpy.deep_learning import TorchRegressorWrapper
from conformalpy.regressor import ConformalRegressor

# Your trained PyTorch regressor
wrapped = TorchRegressorWrapper(pytorch_regressor)

cr = ConformalRegressor(model=wrapped, alpha=0.1)
cr.calibrate(X_calib, y_calib)
intervals = cr.predict_interval(X_test)

# The wrappers automatically handle:
# - Input conversion to appropriate tensor type
# - Batching for memory efficiency
# - Output flattening for regression

Key Features

  1. Lazy Loading: PyTorch/Keras are only imported when you use the corresponding wrapper, not when importing conformalpy.

  2. sklearn Compatibility: Wrappers implement __sklearn_is_fitted__ to pass sklearn’s fitted checks.

  3. Automatic Activation: For classifiers, output activation can be auto-detected from the model architecture.

  4. Device Management: PyTorch wrapper supports GPU acceleration with the device parameter.

  5. Batch Processing: Both wrappers support configurable batch_size for efficient inference on large datasets.

Code
print("Deep learning integration complete!")