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
UserWarningand 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
Xin length. Exactly two classes are required; choosinglabel_posdetermines 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 onX/labels), a list or tuple of such estimators (ensemble; uncertainty = their disagreement), a fittedAAPred, orNone. IfNone, fit a defaultRandomForestClassifier.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_domainboundary (stored asad_threshold_). Must be finite and between 1 and 100, inclusive.ad_borderline (float, default=0.1) –
Width of the
borderlineband just outside the domain boundary, relative to it: a sample with1 < ood_score <= 1 + ad_borderlinegetsad_status='borderline', above that'outside'.0disables 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.90for a 90% interval), matchingModelEvaluator.run(); a finite value in that open interval is required.Changed in version 1.2.0: Now a fraction in
(0, 1)(default0.90) instead of a percent (90.0), matchingModelEvaluator.run()andcomp_bootstrap_ci. A percent value raises aValueErrorwith a hint; the interval itself is unchanged.n_bootstrap (int, default=20) – Bootstrap resamples for uncertainty when
modelis a single estimator (not an ensemble);scoreis then the bagged mean over the resamples (see Notes).0disables 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 forscore_calibrated,margin, andentropy. If fitting fails, emit aUserWarningand leavescore_calibratedasNaN; ifFalse,score_calibratedisNaNand sharpness usesscore.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 - alphacoverage), from 0 through 1 inclusive.
- Returns:
self – The fitted instance.
- Return type:
- Raises:
ValueError – If
X/labelsare invalid or have different lengths,labelsare not binary,label_posis absent fromlabels,modelis an empty list or lackspredict_proba, a passedAAPredis not fitted,calibration_methodis not'isotonic'or'sigmoid', or a numeric parameter is out of range or not finite (NaN/inf), including a negativead_borderline.
Warning
- UserWarning
If
calibrate=Truebut 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_calibratedis thenNaNandeval()withuse_calibrated=Trueraises, naming that reason.Changed in version 1.2.0.
Changed in version 1.2.0: Adds
ad_borderlineand 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.55coin-flip (a real, in-distribution ambiguity) and worthless on a1.0for an input unlike anything it was trained on.ReliabilityModelreturns 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,entropyon a calibrated scoreepistemic
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 coversfit; 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=Nonea default random forest is fitted and its bootstrap disagreement becomes the uncertainty.verboseandrandom_stateare set on the constructor (random_statemakes 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 asmodel— 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 scoredapplicability domain:
k(nearest neighbors),ad_percentile(in-domain boundary),ad_borderline(width of theborderlineband 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(the1 - alphaconformal 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.
fitstores the boundary behindood_scoreasad_threshold_: thead_percentile-th percentile of the training samples’ mean distance to theirknearest training neighbors (standardized features).ad_method_names the decision rule (always"knn"). When this threshold is positive, a new sample’sood_scoreis itsad_knndistance divided by it, so1.0is the boundary;ad_borderline=0.1labels scores up to1.1asborderlineinstead ofoutside. 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