This example demonstrates how to use MultiLabelConformalClassifier to control risk in multi-label classification using three methods:
CRC : Conformal Risk Control (expectation guarantee)
RCPS : Risk-Controlling Prediction Sets (high-probability guarantee)
LTT : Learn Then Test (works with non-monotone losses)
The key difference from single-label conformal prediction is that multi-label problems require per-label thresholding and can control losses beyond coverage, including recall, precision, and F1.
Setup
Generate synthetic multi-label data and train a classifier.
Code
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
from conformalpy.risk_control import (
MultiLabelConformalClassifier,
multilabel_precision_loss,
multilabel_recall_loss,
)
# Generate data
rng = np.random.RandomState(42 )
n_samples, n_features, n_labels = 1500 , 15 , 6
X = rng.randn(n_samples, n_features)
W = rng.randn(n_features, n_labels) * 0.5
logits = X @ W
probs = 1.0 / (1.0 + np.exp(- logits))
y = (rng.rand(n_samples, n_labels) < probs).astype(int )
# Split
X_train, X_calib, X_test = X[:500 ], X[500 :1000 ], X[1000 :]
y_train, y_calib, y_test = y[:500 ], y[500 :1000 ], y[1000 :]
# Train model
model = OneVsRestClassifier(LogisticRegression(max_iter= 500 , random_state= 42 ))
model.fit(X_train, y_train)
print (f"Labels: { n_labels} " )
print (f"Avg labels per sample: { y_test. sum (axis= 1 ). mean():.2f} " )
Labels: 6
Avg labels per sample: 2.97
CRC: Control Recall Loss
CRC provides E[1 - recall] <= alpha, the tightest method for monotone losses.
Code
alpha = 0.15
crc = MultiLabelConformalClassifier(model= model, alpha= alpha, method= "crc" , loss= "recall" )
crc.calibrate(X_calib, y_calib)
pred_crc = crc.predict(X_test)
risk_crc = multilabel_recall_loss(y_test, pred_crc).mean()
avg_labels_crc = pred_crc.sum (axis= 1 ).mean()
print (" \n --- CRC (recall control) ---" )
print (f"Target risk: { alpha} " )
print (f"Empirical recall loss: { risk_crc:.3f} " )
print (f"Empirical recall: { 1 - risk_crc:.3f} " )
print (f"Avg labels predicted: { avg_labels_crc:.2f} " )
print (f"Calibrated lambda: { crc. lambda_:.4f} " )
--- CRC (recall control) ---
Target risk: 0.15
Empirical recall loss: 0.146
Empirical recall: 0.854
Avg labels predicted: 3.53
Calibrated lambda: 0.6131
RCPS: High-Probability Guarantee
RCPS provides P(recall_loss <= alpha) >= 1 - delta. More conservative than CRC but with stronger guarantee.
Code
rcps = MultiLabelConformalClassifier(model= model, alpha= alpha, method= "rcps" , loss= "recall" , delta= 0.1 )
rcps.calibrate(X_calib, y_calib)
pred_rcps = rcps.predict(X_test)
risk_rcps = multilabel_recall_loss(y_test, pred_rcps).mean()
avg_labels_rcps = pred_rcps.sum (axis= 1 ).mean()
print (" \n --- RCPS (recall control, high-probability) ---" )
print (f"Target risk: { alpha} , delta: 0.1" )
print (f"Empirical recall loss: { risk_rcps:.3f} " )
print (f"Avg labels predicted: { avg_labels_rcps:.2f} " )
print (f"Calibrated lambda: { rcps. lambda_:.4f} " )
--- RCPS (recall control, high-probability) ---
Target risk: 0.15, delta: 0.1
Empirical recall loss: 0.000
Avg labels predicted: 6.00
Calibrated lambda: 1.0000
LTT: Precision Control (Non-Monotone)
LTT can control non-monotone losses like precision, which CRC and RCPS cannot handle.
Code
ltt = MultiLabelConformalClassifier(model= model, alpha= 0.3 , method= "ltt" , loss= "precision" , delta= 0.1 )
ltt.calibrate(X_calib, y_calib)
pred_ltt = ltt.predict(X_test)
risk_ltt = multilabel_precision_loss(y_test, pred_ltt).mean()
avg_labels_ltt = pred_ltt.sum (axis= 1 ).mean()
print (" \n --- LTT (precision control) ---" )
print ("Target precision loss: 0.3" )
print (f"Empirical precision loss: { risk_ltt:.3f} " )
print (f"Empirical precision: { 1 - risk_ltt:.3f} " )
print (f"Avg labels predicted: { avg_labels_ltt:.2f} " )
--- LTT (precision control) ---
Target precision loss: 0.3
Empirical precision loss: 0.248
Empirical precision: 0.752
Avg labels predicted: 3.08
Risk Curves Comparison
Compare how risk varies with lambda for each method.
Code
fig, axes = plt.subplots(1 , 2 , figsize= (12 , 5 ))
# Recall loss curve
for mlcc, label, color in [
(crc, "CRC" , "#1f77b4" ),
(rcps, "RCPS" , "#ff7f0e" ),
]:
lambdas, risks = mlcc.get_risk_curve()
axes[0 ].plot(lambdas, risks, label= label, color= color, linewidth= 2 )
axes[0 ].axvline(mlcc.lambda_, color= color, linestyle= "--" , alpha= 0.5 )
axes[0 ].axhline(y= alpha, color= "red" , linestyle= ":" , label= f"Target (alpha= { alpha} )" )
axes[0 ].set_xlabel("Lambda (threshold)" )
axes[0 ].set_ylabel("Average Recall Loss" )
axes[0 ].set_title("Recall Risk Curves" )
axes[0 ].legend()
axes[0 ].grid(True , alpha= 0.3 )
# Precision loss curve (LTT)
lambdas, risks = ltt.get_risk_curve()
axes[1 ].plot(lambdas, risks, label= "LTT" , color= "#2ca02c" , linewidth= 2 )
axes[1 ].axvline(ltt.lambda_, color= "#2ca02c" , linestyle= "--" , alpha= 0.5 )
axes[1 ].axhline(y= 0.3 , color= "red" , linestyle= ":" , label= "Target (alpha=0.3)" )
axes[1 ].set_xlabel("Lambda (threshold)" )
axes[1 ].set_ylabel("Average Precision Loss" )
axes[1 ].set_title("Precision Risk Curve (LTT)" )
axes[1 ].legend()
axes[1 ].grid(True , alpha= 0.3 )
fig.suptitle("Multi-Label Risk Control: Risk vs Lambda" , fontsize= 14 )
plt.tight_layout()
plt.show()
Method Comparison Summary
Code
print (" \n --- Summary ---" )
print (f" { 'Method' :<10} { 'Loss' :<12} { 'Risk' :<8} { 'Avg Labels' :<12} { 'Lambda' :<8} " )
print ("-" * 50 )
print (f" { 'CRC' :<10} { 'recall' :<12} { risk_crc:<8.3f} { avg_labels_crc:<12.2f} { crc. lambda_:<8.4f} " )
print (f" { 'RCPS' :<10} { 'recall' :<12} { risk_rcps:<8.3f} { avg_labels_rcps:<12.2f} { rcps. lambda_:<8.4f} " )
print (f" { 'LTT' :<10} { 'precision' :<12} { risk_ltt:<8.3f} { avg_labels_ltt:<12.2f} { ltt. lambda_:<8.4f} " )
--- Summary ---
Method Loss Risk Avg Labels Lambda
--------------------------------------------------
CRC recall 0.146 3.53 0.6131
RCPS recall 0.000 6.00 1.0000
LTT precision 0.248 3.08 0.5126