ReliabilityModel.fit

ReliabilityModel.fit(X, labels, *, model=None, label_pos=1, k=5, ad_percentile=95.0, ad_borderline=0.1, ci=0.9, n_bootstrap=20, calibrate=True, calibration_method='isotonic', conformal_alpha=0.1)[source]

Fit the reliability reference from a (fitted or default) model and its training data.

Learns, once, everything predict() needs: the applicability-domain reference, the ensemble / bootstrap source of uncertainty, an optional probability calibrator, and the split-conformal calibration.

Changed in version 1.2.0: When calibration was requested but cannot be fitted, emit a UserWarning and record why calibrated evaluation is unavailable.

Parameters:
  • X (array-like, shape (n_samples, n_features)) – Training feature matrix with at least three rows and two features; it must not contain only identical rows. It is the applicability-domain reference and the data used when fitting a default model.

  • labels (array-like of int, shape (n_samples,)) – Integer training labels matching X in length. Exactly two classes are required; choosing label_pos determines which class is scored as positive.

  • model (estimator, list or tuple of estimators, AAPred, or None, default=None) – A scikit-learn classifier with predict_proba (an unfitted estimator is fitted on X / labels), a list or tuple of such estimators (ensemble; uncertainty = their disagreement), a fitted AAPred, or None. If None, fit a default RandomForestClassifier.

  • label_pos (int, default=1) – Non-negative positive-class label whose probability is scored. It must occur in labels.

  • k (int, default=5) – Positive number of nearest training neighbors used for the applicability-domain distance; values above the available training neighbors are capped.

  • ad_percentile (float, default=95.0) – Training kNN-distance percentile used as the in_domain boundary (stored as ad_threshold_). Must be finite and between 1 and 100, inclusive.

  • ad_borderline (float, default=0.1) –

    Width of the borderline band just outside the domain boundary, relative to it: a sample with 1 < ood_score <= 1 + ad_borderline gets ad_status='borderline', above that 'outside'. 0 disables the band. Must be a finite non-negative number (a negative value, inf, NaN, or a bool raises).

    Added in version 1.2.0.

  • ci (float, default=0.90) –

    Central width of the reported score confidence interval, as a fraction in (0, 1) (e.g. 0.90 for a 90% interval), matching ModelEvaluator.run(); a finite value in that open interval is required.

    Changed in version 1.2.0: Now a fraction in (0, 1) (default 0.90) instead of a percent (90.0), matching ModelEvaluator.run() and comp_bootstrap_ci. A percent value raises a ValueError with a hint; the interval itself is unchanged.

  • n_bootstrap (int, default=20) – Bootstrap resamples for uncertainty when model is a single estimator (not an ensemble); score is then the bagged mean over the resamples (see Notes). 0 disables the bootstrap and reports the model’s own probability (score_std = 0). Must be a non-negative integer.

  • calibrate (bool, default=True) – If True, fit a probability calibrator for score_calibrated, margin, and entropy. If fitting fails, emit a UserWarning and leave score_calibrated as NaN; if False, score_calibrated is NaN and sharpness uses score.

  • calibration_method ({'isotonic', 'sigmoid'}, default='isotonic') –

    Calibration method passed to CalibratedClassifierCV.

    • 'isotonic': fit a non-parametric monotonic calibration curve.

    • 'sigmoid': fit Platt’s sigmoid calibration curve.

  • conformal_alpha (float, default=0.1) – Finite miscoverage level of the split-conformal set (1 - alpha coverage), from 0 through 1 inclusive.

Returns:

self – The fitted instance.

Return type:

ReliabilityModel

Raises:

ValueError – If X / labels are invalid or have different lengths, labels are not binary, label_pos is absent from labels, model is an empty list or lacks predict_proba, a passed AAPred is not fitted, calibration_method is not 'isotonic' or 'sigmoid', or a numeric parameter is out of range or not finite (NaN / inf), including a negative ad_borderline.

Warning

UserWarning

If calibrate=True but no calibrator can be fitted, for example because a class holds fewer members than the internal cross-validation needs or the model cannot be cloned. score_calibrated is then NaN and eval() with use_calibrated=True raises, naming that reason.

Changed in version 1.2.0.

Changed in version 1.2.0: Adds ad_borderline and reports a warning when requested calibration is unavailable.

Examples

A prediction score and its trustworthiness are different things. A model can be confident that a case is a 0.55 coin-flip (a real, in-distribution ambiguity) and worthless on a 1.0 for an input unlike anything it was trained on. ReliabilityModel returns the score together with the signals that decide whether to believe it — along two independent axes (the aleatoric vs. epistemic distinction):

axis

what it means

measures

aleatoric

irreducible, in-distribution ambiguity (a genuine 0.55)

margin, entropy on a calibrated score

epistemic

the model’s lack of knowledge — out-of-distribution / sparse data

ood_score / in_domain (applicability domain) + score_std (stability)

So confident-about-0.55 (low epistemic, high aleatoric) is trustworthy as “ambiguous”, while worthless-about-1.0 (high epistemic / out-of-distribution) is not trustworthy at any score. The headline flag reliable = in-domain and a confident conformal singleton.

Workflow: fit (learn the references) -> predict (score new samples) -> eval (calibration + coverage diagnostics) -> :class:~aaanalysis.ReliabilityModelPlot. This notebook covers fit; the others cover the rest.

import aaanalysis as aa
import numpy as np
from sklearn.datasets import make_classification
aa.options["verbose"] = False
# ``X`` is any feature matrix — e.g. a CPP feature matrix from
# ``SequenceFeature.feature_matrix`` — and ``labels`` are binary. A compact synthetic
# stand-in is used here so the example runs in a second.
X, labels = make_classification(n_samples=140, n_features=10, n_informative=6, random_state=42)
X_train, labels_train, X_new = X[:110], labels[:110], X[110:]

Simplest form. With model=None a default random forest is fitted and its bootstrap disagreement becomes the uncertainty. verbose and random_state are set on the constructor (random_state makes the bootstrap / calibration / conformal splits reproducible).

rm = aa.ReliabilityModel(random_state=42, verbose=False).fit(X=X_train, labels=labels_train)

Bring your own model. Pass a fitted scikit-learn classifier, a fitted :class:~aaanalysis.AAPred, or a list of fitted estimators as model — a list uses the members’ disagreement as the uncertainty instead of the bootstrap.

from sklearn.ensemble import RandomForestClassifier
models = [RandomForestClassifier(n_estimators=50, random_state=i).fit(X_train, labels_train)
          for i in range(4)]
rm = aa.ReliabilityModel(random_state=42).fit(X=X_train, labels=labels_train, model=models)

Every parameter, grouped. The remaining parameters tune each axis:

  • label_pos — the positive class whose probability is scored

  • applicability domain: k (nearest neighbors), ad_percentile (in-domain boundary), ad_borderline (width of the borderline band just above that boundary)

  • stability: ci (interval width as a fraction, e.g. 0.90), n_bootstrap (resamples for a single-model uncertainty)

  • calibration: calibrate, calibration_method ("isotonic" or "sigmoid")

  • validity: conformal_alpha (the 1 - alpha conformal coverage level)

rm = aa.ReliabilityModel(random_state=42).fit(
    X=X_train, labels=labels_train, model=None, label_pos=1,
    k=5, ad_percentile=95, ad_borderline=0.1,   # applicability domain
    ci=0.90, n_bootstrap=20,                      # stability
    calibrate=True, calibration_method="isotonic",  # calibration
    conformal_alpha=0.1)                          # conformal validity

Inspect the fitted domain boundary. fit stores the boundary behind ood_score as ad_threshold_: the ad_percentile-th percentile of the training samples’ mean distance to their k nearest training neighbors (standardized features). ad_method_ names the decision rule (always "knn"). When this threshold is positive, a new sample’s ood_score is its ad_knn distance divided by it, so 1.0 is the boundary; ad_borderline=0.1 labels scores up to 1.1 as borderline instead of outside. Record the threshold next to the model to make applicability-domain verdicts reproducible.

import pandas as pd
df_ad = pd.DataFrame({"ad_method_": [rm.ad_method_], "ad_threshold_": [rm.ad_threshold_]})
aa.display_df(df_ad, n_rows=10, show_shape=True)
DataFrame shape: (1, 2)
  ad_method_ ad_threshold_
1 knn 3.158966