mapie.classification.MapieClassifier¶
- class mapie.classification.MapieClassifier(estimator: Optional[sklearn.base.ClassifierMixin] = None, method: str = 'score', cv: Optional[Union[int, str, sklearn.model_selection._split.BaseCrossValidator]] = None, test_size: Optional[Union[int, float]] = None, n_jobs: Optional[int] = None, random_state: Optional[Union[numpy.random.mtrand.RandomState, int]] = None, verbose: int = 0)[source]¶
Prediction sets for classification.
This class implements several conformal prediction strategies for estimating prediction sets for classification. Instead of giving a single predicted label, the idea is to give a set of predicted labels (or prediction sets) which come with mathematically guaranteed coverages.
- Parameters
- estimatorOptional[ClassifierMixin]
Any classifier with scikit-learn API (i.e. with fit, predict, and predict_proba methods), by default None. If
None, estimator defaults to aLogisticRegressioninstance.- method: Optional[str]
Method to choose for prediction interval estimates. Choose among:
“naive”, sum of the probabilities until the 1-alpha thresold.
“score”, based on the the scores (i.e. 1 minus the softmax score of the true label) on the calibration set. See [1] for more details.
“cumulated_score”, based on the sum of the softmax outputs of the labels until the true label is reached, on the calibration set. See [2] for more details.
“raps”, Regularized Adaptive Prediction Sets method. It uses the same technique as cumulated_score method but with a penalty term to reduce the size of prediction sets. See [3] for more details. For now, this method only works with “prefit” and “split” strategies.
“top_k”, based on the sorted index of the probability of the true label in the softmax outputs, on the calibration set. In case two probabilities are equal, both are taken, thus, the size of some prediction sets may be different from the others. See [3] for more details.
By default “score”.
- cv: Optional[str]
The cross-validation strategy for computing scores. It directly drives the distinction between jackknife and cv variants. Choose among:
None, to use the default 5-fold cross-validationinteger, to specify the number of folds. If equal to -1, equivalent to
sklearn.model_selection.LeaveOneOut().CV splitter: any
sklearn.model_selection.BaseCrossValidatorMain variants are: -sklearn.model_selection.LeaveOneOut(jackknife), -sklearn.model_selection.KFold(cross-validation)"split", does not involve cross-validation but a division of the data into training and calibration subsets. The splitter used is the following:sklearn.model_selection.ShuffleSplit."prefit", assumes thatestimatorhas been fitted already. All data provided in thefitmethod is then used to calibrate the predictions through the score computation. At prediction time, quantiles of these scores are used to estimate prediction sets.
By default
None.- test_size: Optional[Union[int, float]]
If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If int, represents the absolute number of test samples. If None, it will be set to 0.1.
If cv is not
"split",test_sizeis ignored.By default
None.- n_jobs: Optional[int]
Number of jobs for parallel processing using joblib via the “locky” backend. At this moment, parallel processing is disabled. If
-1all CPUs are used. If1is given, no parallel computing code is used at all, which is useful for debugging. For n_jobs below-1,(n_cpus + 1 + n_jobs)are used. None is a marker for unset that will be interpreted asn_jobs=1(sequential execution).By default
None.- random_state: Optional[Union[int, RandomState]]
Pseudo random number generator state used for random uniform sampling for evaluation quantiles and prediction sets in cumulated_score. Pass an int for reproducible output across multiple function calls.
By default
None.- verboseint, optional
The verbosity level, used with joblib for multiprocessing. At this moment, parallel processing is disabled. The frequency of the messages increases with the verbosity level. If it more than
10, all iterations are reported. Above50, the output is sent to stdout.By default
0.
References
[1] Mauricio Sadinle, Jing Lei, and Larry Wasserman. “Least Ambiguous Set-Valued Classifiers with Bounded Error Levels.”, Journal of the American Statistical Association, 114, 2019.
[2] Yaniv Romano, Matteo Sesia and Emmanuel J. Candès. “Classification with Valid and Adaptive Coverage.” NeurIPS 202 (spotlight) 2020.
[3] Anastasios Nikolas Angelopoulos, Stephen Bates, Michael Jordan and Jitendra Malik. “Uncertainty Sets for Image Classifiers using Conformal Prediction.” International Conference on Learning Representations 2021.
Examples
>>> import numpy as np >>> from sklearn.naive_bayes import GaussianNB >>> from mapie.classification import MapieClassifier >>> X_toy = np.arange(9).reshape(-1, 1) >>> y_toy = np.stack([0, 0, 1, 0, 1, 2, 1, 2, 2]) >>> clf = GaussianNB().fit(X_toy, y_toy) >>> mapie = MapieClassifier(estimator=clf, cv="prefit").fit(X_toy, y_toy) >>> _, y_pi_mapie = mapie.predict(X_toy, alpha=0.2) >>> print(y_pi_mapie[:, :, 0]) [[ True False False] [ True False False] [ True True False] [ True True False] [False True False] [False True True] [False True True] [False False True] [False False True]]
- Attributes
- valid_methods: List[str]
List of all valid methods.
- single_estimator_sklearn.ClassifierMixin
Estimator fitted on the whole training set.
- n_features_in_: int
Number of features passed to the fit method.
- conformity_scores_ArrayLike of shape (n_samples_train)
The conformity scores used to calibrate the prediction sets.
- quantiles_ArrayLike of shape (n_alpha)
The quantiles estimated from
conformity_scores_and alpha values.
- __init__(estimator: Optional[sklearn.base.ClassifierMixin] = None, method: str = 'score', cv: Optional[Union[int, str, sklearn.model_selection._split.BaseCrossValidator]] = None, test_size: Optional[Union[int, float]] = None, n_jobs: Optional[int] = None, random_state: Optional[Union[numpy.random.mtrand.RandomState, int]] = None, verbose: int = 0) None[source]¶
- fit(X: Union[numpy._typing._array_like._SupportsArray[numpy.dtype], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[Union[bool, int, float, complex, str, bytes]]], y: Union[numpy._typing._array_like._SupportsArray[numpy.dtype], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[Union[bool, int, float, complex, str, bytes]]], sample_weight: Optional[Union[numpy._typing._array_like._SupportsArray[numpy.dtype], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[Union[bool, int, float, complex, str, bytes]]]] = None, size_raps: Optional[float] = 0.2) mapie.classification.MapieClassifier[source]¶
Fit the base estimator or use the fitted base estimator.
- Parameters
- XArrayLike of shape (n_samples, n_features)
Training data.
- yNDArray of shape (n_samples,)
Training labels.
- sample_weightOptional[ArrayLike] of shape (n_samples,)
Sample weights for fitting the out-of-fold models. If None, then samples are equally weighted. If some weights are null, their corresponding observations are removed before the fitting process and hence have no prediction sets.
By default None.
- size_raps: Optional[float]
Percentage of the data to be used for choosing lambda_star and k_star for the RAPS method.
By default .2.
- Returns
- MapieClassifier
The model itself.
- predict(X: Union[numpy._typing._array_like._SupportsArray[numpy.dtype], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[Union[bool, int, float, complex, str, bytes]]], alpha: Optional[Union[float, Iterable[float]]] = None, include_last_label: Optional[Union[bool, str]] = True, agg_scores: Optional[str] = 'mean') Union[numpy.ndarray[Any, numpy.dtype[numpy._typing._generic_alias.ScalarType]], Tuple[numpy.ndarray[Any, numpy.dtype[numpy._typing._generic_alias.ScalarType]], numpy.ndarray[Any, numpy.dtype[numpy._typing._generic_alias.ScalarType]]]][source]¶
Prediction prediction sets on new samples based on target confidence interval. Prediction sets for a given
alphaare deduced from :quantiles of softmax scores (“score” method)
quantiles of cumulated scores (“cumulated_score” method)
- Parameters
- XArrayLike of shape (n_samples, n_features)
Test data.
- alpha: Optional[Union[float, Iterable[float]]]
Can be a float, a list of floats, or a
ArrayLikeof floats. Between 0 and 1, represent the uncertainty of the confidence interval. Loweralphaproduce larger (more conservative) prediction sets.alphais the complement of the target coverage level. By defaultNone.- include_last_label: Optional[Union[bool, str]]
Whether or not to include last label in prediction sets for the “cumulated_score” method. Choose among:
False, does not include label whose cumulated score is just over the quantile.
True, includes label whose cumulated score is just over the quantile, unless there is only one label in the prediction set.
“randomized”, randomly includes label whose cumulated score is just over the quantile based on the comparison of a uniform number and the difference between the cumulated score of the last label and the quantile.
When set to
TrueorFalse, it may result in a coverage higher than1 - alpha(because contrary to the “randomized” setting, none of this methods create empty prediction sets). See [2] and [3] for more details.By default
True.- agg_scores: Optional[str]
How to aggregate the scores output by the estimators on test data if a cross-validation strategy is used. Choose among:
“mean”, take the mean of scores.
“crossval”, compare the scores between all training data and each test point for each label to estimate if the label must be included in the prediction set. Follows algorithm 2 of Romano+2020.
By default “mean”.
- Returns
- Union[NDArray, Tuple[NDArray, NDArray]]
- NDArray of shape (n_samples,) if alpha is None.
- Tuple[NDArray, NDArray] of shapes
- (n_samples,) and (n_samples, n_classes, n_alpha) if alpha is not None.