MLflow Integration for Experiment Tracking

This example demonstrates how to use conformalpy with MLflow for experiment tracking and reproducibility.

conformalpy provides built-in MLflow integration that automatically logs calibration parameters, nonconformity score statistics, and prediction metrics to your MLflow experiments.

Note: MLflow is an optional dependency. Install with: pip install conformalpy[mlflow] or pip install mlflow. The example gracefully handles the case where MLflow is not installed.

Installation:

pip install conformalpy[mlflow]

Setup

First, let’s create a simple classification problem and train a base model.

Code
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

# Create synthetic data
X, y = make_classification(
    n_samples=2000,
    n_features=20,
    n_informative=10,
    n_redundant=5,
    random_state=42,
)

# Split into train, calibration, and test sets
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.4, random_state=42)
X_calib, X_test, y_calib, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)

print(f"Train: {len(y_train)}, Calibration: {len(y_calib)}, Test: {len(y_test)}")

# Train base model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
Train: 1200, Calibration: 400, Test: 400
RandomForestClassifier(random_state=42)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

Using the Verbose Parameter

All conformalpy estimators support a verbose parameter for logging progress. This works independently of MLflow.

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

# Create classifier with verbose=2 for statistics logging
cc = ConformalClassifier(
    model=model,
    alpha=0.1,
    nonconformity_function=lac_nonconformity,
    verbose=2,  # 0=silent, 1=events, 2=stats, 3+=debug
)

# Calibrate - verbose output shows qhat and score statistics
scores = cc.calibrate(X_calib, y_calib)
[conformalpy.ConformalClassifier] Calibrating on 400 samples, alpha=0.1, mode=standard
[conformalpy.ConformalClassifier] qhat=0.4900, score_mean=0.2278, score_std=0.1675

MLflow Integration with Callbacks

The ConformalMLflowCallback automatically logs metrics to MLflow. Let’s check if MLflow is available and demonstrate the integration.

Code
try:
    import mlflow

    from conformalpy.integrations.mlflow import ConformalMLflowCallback

    MLFLOW_AVAILABLE = True
    print("MLflow is available!")
except ImportError:
    MLFLOW_AVAILABLE = False
    print("MLflow not installed. Install with: pip install conformalpy[mlflow]")
MLflow is available!

Example: Full MLflow Experiment

When MLflow is available, you can track your conformal prediction experiments.

Code
if MLFLOW_AVAILABLE:
    # Set up MLflow experiment
    mlflow.set_experiment("conformal_prediction_demo")

    with mlflow.start_run(run_name="rf_conformal_alpha_0.1"):
        # Create callback for automatic logging
        callback = ConformalMLflowCallback(
            log_params=True,  # Log estimator parameters
            log_metrics=True,  # Log calibration and prediction metrics
        )

        # Create conformal classifier with callback
        cc = ConformalClassifier(
            model=model,
            alpha=0.1,
            nonconformity_function=lac_nonconformity,
            callbacks=[callback],
            verbose=1,
        )

        # Calibrate - automatically logs params and calibration metrics
        cc.calibrate(X_calib, y_calib)

        # Predict - automatically logs prediction statistics
        pred_sets = cc.predict(X_test)

        # Compute and log coverage manually if needed
        coverage = cc.score(X_test, y_test)
        mlflow.log_metric("test_coverage", coverage)

        print(f"Test coverage: {coverage:.3f}")
        print(f"Average set size: {np.mean([len(s) for s in pred_sets]):.2f}")

    print("\nMetrics logged to MLflow!")
[conformalpy.ConformalClassifier] Calibrating on 400 samples, alpha=0.1, mode=standard
[conformalpy.ConformalClassifier] Predicted 400 samples
[conformalpy.ConformalClassifier] Predicted 400 samples
Test coverage: 0.915
Average set size: 0.99

Metrics logged to MLflow!

Comparing Multiple Alpha Values

Use prefixes to track multiple configurations in the same run.

Code
if MLFLOW_AVAILABLE:
    alphas = [0.05, 0.10, 0.20]

    with mlflow.start_run(run_name="multi_alpha_comparison"):
        for alpha in alphas:
            # Use prefixes to distinguish metrics across alphas
            prefix = f"alpha{int(alpha * 100):02d}_"
            callback = ConformalMLflowCallback(
                calibration_prefix=f"{prefix}cal_",
                prediction_prefix=f"{prefix}test_",
            )

            cc = ConformalClassifier(
                model=model,
                alpha=alpha,
                nonconformity_function=lac_nonconformity,
                callbacks=[callback],
            )
            cc.calibrate(X_calib, y_calib)

            # Log test metrics
            coverage = cc.score(X_test, y_test)
            pred_sets = cc.predict(X_test)
            avg_size = np.mean([len(s) for s in pred_sets])

            mlflow.log_metrics(
                {
                    f"{prefix}test_coverage": coverage,
                    f"{prefix}test_avg_set_size": avg_size,
                }
            )

            print(f"Alpha={alpha}: coverage={coverage:.3f}, avg_size={avg_size:.2f}")
Alpha=0.05: coverage=0.950, avg_size=1.07
Alpha=0.1: coverage=0.915, avg_size=0.99
Alpha=0.2: coverage=0.782, avg_size=0.81

Manual Logging Functions

For more control, use the standalone logging functions.

Code
if MLFLOW_AVAILABLE:
    from conformalpy.integrations.mlflow import log_calibration, log_prediction

    with mlflow.start_run(run_name="manual_logging"):
        # Create and calibrate without callback
        cc = ConformalClassifier(
            model=model,
            alpha=0.1,
            nonconformity_function=lac_nonconformity,
        )
        scores = cc.calibrate(X_calib, y_calib)

        # Manually log calibration with custom prefix
        log_calibration(cc, scores, prefix="calib_")

        # Predict and log
        pred_sets = cc.predict(X_test)
        log_prediction(pred_sets, y_test, prefix="test_")

        print("Manual logging complete!")
Manual logging complete!

Regression Example

MLflow integration also works with regression.

Code
from sklearn.datasets import make_regression
from sklearn.ensemble import RandomForestRegressor

from conformalpy.regressor import ConformalRegressor

# Create regression data
X_reg, y_reg = make_regression(n_samples=1000, n_features=10, random_state=42)
X_train_r, X_temp_r, y_train_r, y_temp_r = train_test_split(X_reg, y_reg, test_size=0.4, random_state=42)
X_calib_r, X_test_r, y_calib_r, y_test_r = train_test_split(X_temp_r, y_temp_r, test_size=0.5, random_state=42)

# Train regressor
reg_model = RandomForestRegressor(n_estimators=50, random_state=42)
reg_model.fit(X_train_r, y_train_r)

if MLFLOW_AVAILABLE:
    with mlflow.start_run(run_name="regression_conformal"):
        callback = ConformalMLflowCallback()

        cr = ConformalRegressor(
            model=reg_model,
            alpha=0.1,
            callbacks=[callback],
            verbose=1,
        )

        cr.calibrate(X_calib_r, y_calib_r)
        intervals = cr.predict_interval(X_test_r)

        # Log test coverage
        coverage = cr.score(X_test_r, y_test_r)
        avg_width = np.mean(intervals[:, 1] - intervals[:, 0])

        mlflow.log_metrics(
            {
                "test_coverage": coverage,
                "test_avg_interval_width": avg_width,
            }
        )

        print(f"Regression - Coverage: {coverage:.3f}, Avg width: {avg_width:.2f}")
[conformalpy.ConformalRegressor] Calibrating on 200 samples, alpha=0.1
[conformalpy.ConformalRegressor] Predicted intervals for 200 samples
[conformalpy.ConformalRegressor] Predicted intervals for 200 samples
Regression - Coverage: 0.930, Avg width: 198.35

Summary

conformalpy’s MLflow integration provides:

  • Automatic parameter logging: All estimator parameters via get_params()
  • Calibration metrics: qhat, score statistics, sample counts
  • Prediction metrics: Set sizes, singleton rates, coverage
  • Flexible prefixes: Track multiple models in the same run
  • Manual control: Standalone functions for custom workflows

This integration enables reproducible conformal prediction experiments with full tracking of hyperparameters and results.

Code
print("\nExample complete!")

Example complete!