Train a Random Forest classifier that provides probability estimates.
Code
model = RandomForestClassifier(n_estimators=100, random_state=42)model.fit(X_train, y_train)# Check base model accuracybase_accuracy = model.score(X_test, y_test)print(f"Base model test accuracy: {base_accuracy:.1%}")
Base model test accuracy: 90.0%
Create and Calibrate Conformal Classifier
Wrap the trained model with conformal prediction.
Code
alpha =0.10# Target coverage: 90%cc = ConformalClassifier( model=model, alpha=alpha, nonconformity_function=lac_nonconformity,)# Calibrate on held-out calibration setcc.calibrate(X_calib, y_calib)# Check stored class informationprint(f"Number of classes detected: {cc.n_classes_}")print(f"Classes: {cc.classes_}")print(f"Calibration threshold (qhat): {cc.get_qhat():.4f}")
Number of classes detected: 3
Classes: [0 1 2]
Calibration threshold (qhat): 0.3340
Generate Prediction Sets
Get conformal prediction sets for the test data.
Code
prediction_sets = cc.predict(X_test)# Show some examplesprint("\nExample predictions (first 10 samples):")print("-"*50)for i inrange(10): pset = prediction_sets[i] true_label = y_test[i] pset_names = [str(class_names[c]) for c insorted(pset)] true_name =str(class_names[true_label]) covered ="✓"if true_label in pset else"✗" set_str ="{"+", ".join(pset_names) +"}"if pset_names else"{}"print(f" True: {true_name:12s} | Predicted: {set_str:30s}{covered}")
The key property of conformal prediction: coverage ≥ 1 - α. Note: With small samples (n=30), there can be variance around the target. The guarantee holds in expectation; larger samples give tighter results.
Code
summary = conformal_classification_summary(prediction_sets, y_test)print(f"\n{'='*50}")print("COVERAGE METRICS")print(f"{'='*50}")print(f"Target coverage (1 - α): {1- alpha:.1%}")print(f"Empirical coverage: {summary['coverage']:.1%}")print(f"Average set size: {summary['avg_set_size']:.2f}")print(f"{'='*50}")# Verify guaranteeif summary["coverage"] >=1- alpha -0.01: # Small tolerance for finite sampleprint("✓ Coverage guarantee satisfied!")else:print("✗ Coverage below target (may happen with small samples)")
Classify samples into decision zones for operational use.
Code
zones = classify_zones(prediction_sets, y_test)zone_stats = zone_summary(prediction_sets, y_test)print("\nOperational Zone Distribution:")print("-"*40)for zone, prop in zone_stats["proportions"].items():print(f" {zone:15s}: {prop:.1%}")
from conformalpy.plots import plot_prediction_set_size_distributionplot_prediction_set_size_distribution(prediction_sets, title="Prediction Set Size Distribution (Iris, 3-class)")plt.tight_layout()plt.show()
Visualize Coverage by Class
Bar chart showing coverage per class with target line.
Code
fig, ax = plt.subplots(figsize=(8, 5))classes =list(class_cov.keys())coverages = [class_cov[c] for c in classes]colors = ["#2ecc71"if c >=1- alpha else"#e74c3c"for c in coverages]bars = ax.bar([class_names[c] for c in classes], coverages, color=colors, edgecolor="black")ax.axhline(y=1- alpha, color="red", linestyle="--", linewidth=2, label=f"Target (1-α = {1- alpha:.0%})")ax.set_xlabel("Class")ax.set_ylabel("Coverage")ax.set_title("Class-Conditional Coverage (Iris Dataset)")ax.set_ylim(0, 1.1)ax.legend()# Add value labels on barsfor bar, cov inzip(bars, coverages): ax.text( bar.get_x() + bar.get_width() /2, bar.get_height() +0.02, f"{cov:.1%}", ha="center", va="bottom", fontsize=10 )plt.tight_layout()plt.show()
Visualize Outcome Distribution
Pie chart of outcome categories.
Code
fig, ax = plt.subplots(figsize=(8, 6))# Count outcomesfrom collections import Counteroutcome_counts = Counter(outcomes)labels = []sizes = []colors_map = {"SC": "#2ecc71", # Green - correct"SI": "#e74c3c", # Red - incorrect"TS0": "#3498db", # Blue - uncertain"TS1": "#9b59b6", # Purple - uncertain"Empty": "#95a5a6", # Gray - empty}# For multiclass, we may have outcomes like "TS0" for covered multi-setsfor outcome in ["SC", "SI", "TS0", "TS1", "Empty"]: count = outcome_counts.get(outcome, 0)if count >0: labels.append(outcome) sizes.append(count)colors = [colors_map.get(l, "#95a5a6") for l in labels]wedges, texts, autotexts = ax.pie( sizes, labels=labels, colors=colors, autopct="%1.1f%%", startangle=90, explode=[0.02] *len(sizes))ax.set_title("Outcome Distribution (Iris Dataset)")plt.tight_layout()plt.show()
Summary
Key takeaways from this multiclass conformal prediction example:
Coverage guarantee holds: Empirical coverage ≥ 1 - α for all classes
Class-conditional coverage: Each class achieves near-target coverage
Efficiency: Most predictions are singletons (high information)
Operational zones: Clear separation into safe/uncertain/problematic
The conformalpy library handles multiclass classification naturally, extending all binary classification functionality to K > 2 classes.