The simplest possible conformal classification example. Train a model, calibrate it, and get prediction sets with coverage guarantees.
This example uses the Iris dataset to demonstrate:
- Splitting data into train/calibration/test
- Training a base classifier
- Calibrating a conformal classifier
- Getting prediction sets with 90% coverage guarantee
Setup
Code
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from conformalpy.classifier import ConformalClassifier
from conformalpy.evaluation import average_set_size, coverage_score
from conformalpy.nonconformity.classification import lac_nonconformity
# Load data and split into train / calibration / test
X, y = load_iris(return_X_y=True)
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 and Calibrate
Code
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
cc = ConformalClassifier(
model=model,
alpha=0.10, # Target: 90% coverage
nonconformity_function=lac_nonconformity,
)
cc.calibrate(X_cal, y_cal)
array([0.01, 0. , 0. , 0. , 0. , 0.01, 0. , 0.08, 0. , 0. , 0.01,
0.05, 0.11, 0.01, 0.02, 0. , 0.06, 0. , 0. , 0.12, 0. , 0.02,
0.06, 0. , 0.11, 0.01, 0. , 0. , 0. , 0. ])
Predict and Evaluate
Code
prediction_sets = cc.predict(X_test)
coverage = coverage_score(prediction_sets, y_test)
avg_size = average_set_size(prediction_sets)
print(f"Coverage: {coverage:.1%} (target: 90%)")
print(f"Average set size: {avg_size:.2f}")
print(f"Example sets: {prediction_sets[:5]}")
Coverage: 93.3% (target: 90%)
Average set size: 0.93
Example sets: [[1], [0], [1], [1], [0]]