classifier.ConformalClassifier

classifier.ConformalClassifier(
    model=None,
    alpha=0.1,
    nonconformity_function=None,
    mondrian=False,
    verbose=0,
    callbacks=None,
)

Split (Inductive) Conformal Classifier.

Wraps a fitted classifier and uses a held-out calibration set to compute nonconformity score thresholds that guarantee finite-sample coverage.

Parameters

model : Any = None

The classification model to use for predictions. Must implement predict_proba() and be already fitted.

alpha : float = 0.1

Significance level for the conformal prediction. Must be in (0, 1). The target coverage is 1 - alpha.

nonconformity_function : Callable = None

Function to compute nonconformity scores. Should have signature func(y_true, y_prob) -> scores. If None, must be set before calling calibrate() or fit().

mondrian : bool = False

Whether to use Mondrian (class-conditional) conformal prediction. If True, separate quantiles are computed for each class, providing class-conditional coverage guarantees as introduced by Vovk et al. (Vovk et al. 2005) (Section 4.1).

verbose : int = 0

Verbosity level: - 0: Silent (default) - 1: Key events (calibration start/end, prediction start/end) - 2: Statistics (qhat, score distributions, set sizes) - 3+: Debug (per-class breakdowns, timing)

callbacks : list = None

List of callback objects for experiment tracking integration. Callbacks can implement on_calibrate_end(estimator, scores) and on_predict_end(prediction_sets, y_true) methods. See conformalpy.integrations.mlflow.ConformalMLflowCallback.

Notes

The calibration step computes a quantile threshold with finite-sample correction:

\[ \hat{q} = \text{Quantile}\left(s_1, \dots, s_n; \frac{\lceil (n+1)(1-\alpha) \rceil}{n}\right) \]

This ensures coverage \(P(Y_{n+1} \in C(X_{n+1})) \geq 1-\alpha\) for exchangeable data (Proposition 2.2 in (Vovk et al. 2005)).

References

  1. Vovk, V., Gammerman, A., & Shafer, G. (2005). Algorithmic Learning in a Random World. Springer.
  2. Papadopoulos, H., Proedrou, K., Vovk, V., & Gammerman, A. (2002). Inductive Confidence Machines for Regression. Machine Learning and Applications, 345–356.

Methods

Name Description
calibrate Calibrate the conformal classifier using a calibration set.
fit Fit (calibrate) the conformal classifier using a calibration set.
get_qhat Get the quantile threshold for the nonconformity scores.
predict Predict conformal prediction sets for the given input data.
predict_p_values Compute conformal p-values for each class for the given input data.
predict_top_k Predict top-K prediction sets for the given input data.
score Compute empirical coverage on test data.

calibrate

classifier.ConformalClassifier.calibrate(X_calib, y_calib, *, groups=None)

Calibrate the conformal classifier using a calibration set.

Parameters

X_calib : array-like of shape (n_samples, n_features)

Calibration features.

y_calib : array-like of shape (n_samples,)

Calibration labels.

groups : array-like of shape (n_samples,) = None

Group labels for Flexible Mondrian calibration. If provided, separate quantiles are computed for each group. This enables per-group coverage guarantees.

Returns

: np.ndarray

Nonconformity scores for the calibration set.

Notes

After calibration, the following attributes are set:

  • classes_ : ndarray of unique class labels
  • n_classes_ : int, number of classes
  • qhat_ : float or dict, calibrated quantile threshold(s)
  • qhat_per_group_ : dict (if groups provided), quantile per group
  • groups_ : ndarray (if groups provided), unique group labels

fit

classifier.ConformalClassifier.fit(X_calib, y_calib)

Fit (calibrate) the conformal classifier using a calibration set.

This is an alias for calibrate() to follow scikit-learn conventions. Enables use with sklearn pipelines, cross-validation, and grid search.

Parameters

X_calib : array-like of shape (n_samples, n_features)

Calibration features.

y_calib : array-like of shape (n_samples,)

Calibration labels.

Returns

self : ConformalClassifier

Returns self for method chaining.

get_qhat

classifier.ConformalClassifier.get_qhat()

Get the quantile threshold for the nonconformity scores.

Returns

: float or dict

The quantile threshold. In Mondrian mode, returns a dict mapping class labels to per-class thresholds.

predict

classifier.ConformalClassifier.predict(X, *, alpha=None, groups=None)

Predict conformal prediction sets for the given input data.

Parameters

X : array-like of shape (n_samples, n_features)

Input features.

alpha : float, list of float, or None = None

Significance level(s) for prediction. If None, uses self.alpha from init. If scalar, returns list[list[int]] as before. If array-like, returns (n_samples, n_classes, n_alphas) bool array where result[i, k, a] = True means class k is in the prediction set for sample i at alpha level a.

groups : array-like of shape (n_samples,) = None

Group labels for Flexible Mondrian prediction. If provided, uses group-specific qhat values. For unseen groups, falls back to global qhat.

Returns

: list of list of int or np.ndarray

If alpha is None or scalar: list of prediction sets per sample. If alpha is array: boolean array of shape (n_samples, n_classes, n_alphas).

predict_p_values

classifier.ConformalClassifier.predict_p_values(
    X,
    *,
    smoothed=False,
    random_state=None,
)

Compute conformal p-values for each class for the given input data.

P-values indicate how conforming each class label is for each sample. Higher p-values mean the class is more plausible given the calibration data.

By default (smoothed=False), the conservative (non-randomized) p-value is returned, which is deterministic and exactly equivalent to the set membership produced by predict(): p_y(x) = (N_greater + N_equal + 1) / (N_cal + 1)

If smoothed=True, the randomized (smoothed) p-value is returned instead, which is exactly valid (not conservative) but not deterministic unless random_state is fixed: p_y(x) = (N_greater + theta * (N_equal + 1)) / (N_cal + 1)

Where: - N_greater : Number of calibration instances i where s_i > s(x,y) - N_equal : Number of calibration instances i where s_i == s(x,y) - theta : Random tie-breaking term sampled from U[0, 1] (smoothed only) - N_cal : Number of calibration instances (filtered by class y if mondrian=True, or total instances if mondrian=False) - s(x,y) : Nonconformity score for the test point assuming class y

Parameters

X : np.ndarray

Input features of shape (n_samples, n_features)

smoothed : bool = False

If True, return the randomized (smoothed) p-value. If False (default), return the conservative p-value, which is deterministic.

random_state : int = None

Seed for the random number generator. Only used when smoothed=True, and also passed through to nonconformity functions that require randomization (e.g. APS/RAPS/SAPS).

Returns

: np.ndarray

P-values of shape (n_samples, n_classes). Each row contains the p-value for each possible class label.

predict_top_k

classifier.ConformalClassifier.predict_top_k(X, k)

Predict top-K prediction sets for the given input data.

Unlike threshold-based conformal prediction, this returns exactly K classes for each sample (the K classes with highest probability / lowest nonconformity score). This is useful when you need fixed-size prediction sets.

Note: Top-K sets do not provide the same coverage guarantees as standard conformal prediction. Use this when fixed set size is more important than coverage guarantees.

Parameters

X : array-like of shape (n_samples, n_features)

Input features.

k : int

Number of classes to include in each prediction set. Must be between 1 and n_classes_.

Returns

: list of list of int

List of prediction sets, each containing exactly k class labels sorted by decreasing probability (increasing nonconformity).

Examples

>>> # Get top-3 classes for each sample
>>> top3_sets = conf_clf.predict_top_k(X_test, k=3)
>>> print(top3_sets[0])  # e.g., [2, 1, 0] - class 2 most likely

See Also

predict : Threshold-based prediction sets with coverage guarantees. predict_p_values : Get p-values for all classes.

score

classifier.ConformalClassifier.score(X, y)

Compute empirical coverage on test data.

Parameters

X : array-like of shape (n_samples, n_features)

Test features.

y : array-like of shape (n_samples,)

True labels.

Returns

: float

Empirical coverage (proportion of prediction sets containing true label).

References

Vovk, Vladimir, Alexander Gammerman, and Glenn Shafer. 2005. Algorithmic Learning in a Random World. Springer. https://doi.org/10.1007/b106715.