ConformalClassifier¶
Read more in the User Guide.
Reference¶
class conformity.ConformalClassifier(
estimator,
*,
method='lac',
auto_calibrate=True,
tts_kwargs=None,
)Split conformal classification using LAC or deterministic APS scores.
Parameters¶
estimatorBaseEstimatorCloneable sklearn classifier implementing predict_proba.
method{'lac', 'aps'}, default='lac'Use lac (1 - probability) or aps (cumulative ranked probability).
auto_calibratebool or None, default=TrueReserve held-out calibration data during fit; defaults to True.
tts_kwargsTrainTestSplitKwargs or None, default=Nonetrain_test_split options for automatic calibration. By default, test_size=0.2, shuffle=True and stratify=None.
Attributes¶
method_{"lac", "aps"}Score method recorded by successful calibration; changing it requires recalibration. Shared fitted attributes are documented on the base class.
Attributes¶
estimator_BaseEstimatorFitted clone; created by fit and removed by parameter changes.
n_features_in_intNumber of validated fitting features.
feature_names_in_ndarrayInput names, present when fitting named string columns.
classes_ndarrayClassifier labels in probability and membership-column order.
calibration_scores_ndarrayImmutable held-out scores; created by successful calibration.
sorted_calibration_scores_ndarrayImmutable sorted scores cached for rank queries.
n_calibration_intNumber of held-out calibration observations.
alpha_used_floatMiscoverage probability from the most recent threshold query.
quantile_level_floatFinite-sample rank divided by calibration count; may exceed one.
q_level_floatMost recent threshold, including infinity when the rank exceeds n.
is_calibrated_boolWhether held-out scores exist. Refitting clears calibration state.
Examples¶
>>> from sklearn.datasets import load_iris
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.pipeline import Pipeline
>>> from sklearn.preprocessing import StandardScaler
>>> from conformity import ConformalClassifier
>>> X, y = load_iris(return_X_y=True)
>>> X_dev, X_test, y_dev, y_test = train_test_split(
... X, y, test_size=0.2, random_state=0
... )
>>> X_train, X_calib, y_train, y_calib = train_test_split(
... X_dev, y_dev, test_size=0.25, random_state=1
... )
>>> model = Pipeline([
... ("scaler", StandardScaler()),
... ("conformal", ConformalClassifier(
... LogisticRegression(max_iter=500), method="lac", auto_calibrate=False
... )),
... ])
>>> _ = model.fit(X_train, y_train)
>>> _ = model[-1].calibrate(model[:-1].transform(X_calib), y_calib)
>>> mask, probabilities = model.predict(X_test, alpha=0.1, return_set=True)
>>> mask.shape, probabilities.shape
((30, 3), (30, 3))
>>> model.classes_.tolist()
[0, 1, 2]
>>> mask.dtype.name
'bool'
Methods¶
| Method | Purpose |
|---|---|
| calibrate | Replace held-out scores and return this predictor for method chaining. |
| evaluate | Return accuracy, log loss, coverage and prediction set diagnostics. |
| fit | Fit a fresh clone; optionally reserve an independent calibration split. |
| get_metadata_routing | Get metadata routing of this object. |
| get_params | Get parameters for this estimator. |
| predict | Return point labels, or (boolean membership sets, probabilities). |
| predict_p_values | Return conservative conformal p-values, including calibration ties. |
| predict_point | Return the wrapped estimator's labels without calibration. |
| predict_proba | Return validated probabilities in classes_ order. |
| predict_set | Return a boolean membership matrix of shape (n_samples, n_classes). |
| score | Return point accuracy using point predictions. |
| set_fit_request | Request metadata passed to the fit method. |
| set_params | Set sklearn parameters and invalidate fitted and calibrated state. |
| set_predict_request | Request metadata passed to the predict method. |
| set_score_request | Request metadata passed to the score method. |
| ### calibrate |
calibrate(X, y)Replace held-out scores and return this predictor for method chaining.
Parameters¶
X{array-like, sparse matrix, DataFrame} of shape (n_samples, n_features)Feature matrix of shape (n_samples, n_features); dense, sparse, or DataFrame.
yarray-like of shape (n_samples,)One target per sample; classification labels follow the fitted classes.
Returns¶
selfobjectPredictor with replacement calibration scores.
Raises¶
ValueErrorIf input shapes, values, weights or configuration are invalid.
NotFittedErrorIf fit has not established a fitted estimator.
evaluate¶
evaluate(
X,
y,
alpha=0.05,
*,
sample_weight=None,
)Return accuracy, log loss, coverage and prediction set diagnostics.
Parameters¶
X{array-like, sparse matrix, DataFrame} of shape (n_samples, n_features)Feature matrix of shape (n_samples, n_features); dense, sparse, or DataFrame.
yarray-like of shape (n_samples,)One target per sample; classification labels follow the fitted classes.
alphafloat, default=0.05Miscoverage probability strictly between zero and one.
sample_weightarray-like of shape (n_samples,) or None, default=NoneOptional finite, nonnegative weights; fitting or evaluation only, never calibration.
Returns¶
reportdict of str to floatKeys are accuracy, log_loss, coverage, mean_size, empty_rate and singleton_rate.
Raises¶
ValueErrorIf input shapes, values, weights or configuration are invalid.
NotFittedErrorIf fit has not established a fitted estimator.
RuntimeErrorIf conformal output is requested before calibration.
fit¶
fit(
X,
y,
auto_calibrate=None,
tts_kwargs=None,
*,
sample_weight=None,
**fit_params,
)Fit a fresh clone; optionally reserve an independent calibration split.
Parameters¶
X{array-like, sparse matrix, DataFrame} of shape (n_samples, n_features)Feature matrix of shape (n_samples, n_features); dense, sparse, or DataFrame.
yarray-like of shape (n_samples,)One target per sample; classification labels follow the fitted classes.
auto_calibratebool or None, default=NoneReserve an independent calibration split when fitting.
tts_kwargsTrainTestSplitKwargs or None, default=Nonetrain_test_split options for this fit; requires automatic calibration. If provided, this mapping replaces the constructor mapping. Missing options use defaults: test_size=0.2, train_size=None, random_state=None, shuffle=True and stratify=None. Set
random_statehere for reproducible automatic splits.sample_weightarray-like of shape (n_samples,) or None, default=NoneOptional finite, nonnegative weights; fitting or evaluation only, never calibration.
**fit_paramsdictEstimator-specific fit metadata forwarded to the cloned estimator.
Returns¶
selfobjectFitted predictor; calibrated when automatic calibration is enabled.
Raises¶
TypeErrorIf the estimator cannot be cloned or lacks the required prediction methods.
ValueErrorIf input shapes, values, weights or configuration are invalid.
get_metadata_routing¶
get_metadata_routing()Get metadata routing of this object.
Returns¶
routingMetadataRequestA :class:`~sklearn.utils.metadata_routing.MetadataRequest` encapsulating routing information.
get_params¶
get_params(deep=True)Get parameters for this estimator.
Parameters¶
deepbool, default=True, default=TrueIf True, will return the parameters for this estimator and contained subobjects that are estimators.
Returns¶
paramsdictParameter names mapped to their values.
predict¶
predict(
X,
alpha=0.05,
*,
return_set=False,
)Return point labels, or (boolean membership sets, probabilities).
Parameters¶
X{array-like, sparse matrix, DataFrame} of shape (n_samples, n_features)Feature matrix of shape (n_samples, n_features); dense, sparse, or DataFrame.
alphafloat, default=0.05Miscoverage probability strictly between zero and one.
return_setbool, default=FalseRequest conformal output alongside ordinary predictions.
Returns¶
predictionsndarray or tuple of ndarrayPoint labels, or (membership, probabilities) when return_set=True.
Raises¶
ValueErrorIf input shapes, values, weights or configuration are invalid.
NotFittedErrorIf fit has not established a fitted estimator.
RuntimeErrorIf conformal output is requested before calibration.
predict_p_values¶
predict_p_values(X)Return conservative conformal p-values, including calibration ties.
Parameters¶
X{array-like, sparse matrix, DataFrame} of shape (n_samples, n_features)Feature matrix of shape (n_samples, n_features); dense, sparse, or DataFrame.
Returns¶
p_valuesndarray of shape (n_samples, n_classes)Conservative conformal p-values in classes_ order, including ties.
Raises¶
ValueErrorIf input shapes, values, weights or configuration are invalid.
NotFittedErrorIf fit has not established a fitted estimator.
RuntimeErrorIf conformal output is requested before calibration.
predict_point¶
predict_point(X)Return the wrapped estimator's labels without calibration.
Parameters¶
X{array-like, sparse matrix, DataFrame} of shape (n_samples, n_features)Feature matrix of shape (n_samples, n_features); dense, sparse, or DataFrame.
Returns¶
predictionsndarray of shape (n_samples,)Point predictions from the fitted estimator.
Raises¶
ValueErrorIf input shapes, values, weights or configuration are invalid.
NotFittedErrorIf fit has not established a fitted estimator.
predict_proba¶
predict_proba(X)Return validated probabilities in classes_ order.
Parameters¶
X{array-like, sparse matrix, DataFrame} of shape (n_samples, n_features)Feature matrix of shape (n_samples, n_features); dense, sparse, or DataFrame.
Returns¶
probabilitiesndarray of shape (n_samples, n_classes)Finite class probabilities in fitted classes_ order.
Raises¶
ValueErrorIf input shapes, values, weights or configuration are invalid.
NotFittedErrorIf fit has not established a fitted estimator.
predict_set¶
predict_set(X, alpha=0.05)Return a boolean membership matrix of shape (n_samples, n_classes).
Parameters¶
X{array-like, sparse matrix, DataFrame} of shape (n_samples, n_features)Feature matrix of shape (n_samples, n_features); dense, sparse, or DataFrame.
alphafloat, default=0.05Miscoverage probability strictly between zero and one.
Returns¶
membershipndarray of bool, shape (n_samples, n_classes)Included labels in classes_ order; empty and all-class sets are permitted.
Raises¶
ValueErrorIf input shapes, values, weights or configuration are invalid.
NotFittedErrorIf fit has not established a fitted estimator.
RuntimeErrorIf conformal output is requested before calibration.
score¶
score(
X,
y,
sample_weight=None,
)Return point accuracy using point predictions.
Parameters¶
X{array-like, sparse matrix, DataFrame} of shape (n_samples, n_features)Feature matrix of shape (n_samples, n_features); dense, sparse, or DataFrame.
yarray-like of shape (n_samples,)One target per sample; classification labels follow the fitted classes.
sample_weightarray-like of shape (n_samples,) or None, default=NoneOptional finite, nonnegative weights; fitting or evaluation only, never calibration.
Returns¶
scorefloatPoint-prediction R² for regression or accuracy for classification.
Raises¶
ValueErrorIf input shapes, values, weights or configuration are invalid.
NotFittedErrorIf fit has not established a fitted estimator.
set_fit_request¶
set_fit_request(
*,
auto_calibrate='$UNCHANGED$',
sample_weight='$UNCHANGED$',
tts_kwargs='$UNCHANGED$',
)Request metadata passed to the fit method.
Parameters¶
auto_calibratestr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED, default='$UNCHANGED$'Metadata routing for
auto_calibrateparameter infit.sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED, default='$UNCHANGED$'Metadata routing for
sample_weightparameter infit.tts_kwargsstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED, default='$UNCHANGED$'Metadata routing for
tts_kwargsparameter infit.
Returns¶
selfobjectThe updated object.
set_params¶
set_params(**params)Set sklearn parameters and invalidate fitted and calibrated state.
Parameters¶
**paramsdictSklearn parameters, including nested estimator parameters.
Returns¶
selfobjectPredictor with updated parameters and invalidated fitted state.
Raises¶
ValueErrorIf input shapes, values, weights or configuration are invalid.
set_predict_request¶
set_predict_request(
*,
alpha='$UNCHANGED$',
return_set='$UNCHANGED$',
)Request metadata passed to the predict method.
Parameters¶
alphastr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED, default='$UNCHANGED$'Metadata routing for
alphaparameter inpredict.return_setstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED, default='$UNCHANGED$'Metadata routing for
return_setparameter inpredict.
Returns¶
selfobjectThe updated object.
set_score_request¶
set_score_request(*, sample_weight='$UNCHANGED$')Request metadata passed to the score method.
Parameters¶
sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED, default='$UNCHANGED$'Metadata routing for
sample_weightparameter inscore.
Returns¶
selfobjectThe updated object.
is_calibrated_¶
Report whether calibration scores are available.