Calibration¶
Calibration methods for probabilistic predictions.
mapie.calibration.TopLabelCalibrator
¶
TopLabelCalibrator(
estimator: Optional[ClassifierMixin] = None,
calibrator: Optional[Union[str, RegressorMixin]] = None,
cv: Optional[str] = "split",
)
Bases: BaseEstimator, ClassifierMixin
Top-label calibration for multi-class problems. Performs a calibration on the class with the highest score given both score and class, see section 2 of [1].
| PARAMETER | DESCRIPTION |
|---|---|
estimator
|
Any classifier with scikit-learn API
(i.e. with fit, predict, and predict_proba methods), by default
TYPE:
|
calibrator
|
Any calibrator with scikit-learn API
(i.e. with fit, predict, and predict_proba methods), by default
By default
TYPE:
|
cv
|
The cross-validation strategy to compute scores :
By default "split".
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
classes_ |
Array with the name of each class.
TYPE:
|
n_classes_ |
Number of classes that are in the training dataset.
TYPE:
|
uncalib_pred |
Array of the uncalibrated predictions set by the
TYPE:
|
single_estimator_ |
Classifier fitted on the training data.
TYPE:
|
calibrators |
Dictionnary of all the fitted calibrators.
TYPE:
|
References
[1] Gupta, Chirag, and Aaditya K. Ramdas. "Top-label calibration and multiclass-to-binary reductions." arXiv preprint arXiv:2107.08353 (2021).
Examples:
>>> import numpy as np
>>> from mapie.calibration import TopLabelCalibrator
>>> X_toy = np.arange(9).reshape(-1, 1)
>>> y_toy = np.stack([0, 0, 1, 0, 1, 2, 1, 2, 2])
>>> mapie = TopLabelCalibrator().fit(X_toy, y_toy, random_state=20)
>>> y_calib = mapie.predict_proba(X_toy)
>>> print(y_calib)
[[0.84...... nan nan]
[0.75...... nan nan]
[0.62...... nan nan]
[ nan 0.33...... nan]
[ nan 0.33...... nan]
[ nan 0.33...... nan]
[ nan nan 0.33......]
[ nan nan 0.54......]
[ nan nan 0.66......]]
Source code in mapie/calibration.py
fit
¶
fit(
X: ArrayLike,
y: ArrayLike,
sample_weight: Optional[NDArray] = None,
calib_size: Optional[float] = 0.33,
random_state: Optional[
Union[int, RandomState, None]
] = None,
shuffle: Optional[bool] = True,
stratify: Optional[ArrayLike] = None,
**fit_params,
) -> TopLabelCalibrator
Calibrate the estimator on given datasets, according to the chosen method.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Training data.
TYPE:
|
y
|
Training labels.
TYPE:
|
sample_weight
|
Sample weights for fitting the out-of-fold models.
If
TYPE:
|
calib_size
|
If
TYPE:
|
random_state
|
TYPE:
|
shuffle
|
See
TYPE:
|
stratify
|
See
TYPE:
|
**fit_params
|
Additional fit parameters.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TopLabelCalibrator
|
The model itself. |
Source code in mapie/calibration.py
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 | |
predict_proba
¶
Prediction of the calibrated scores using fitted classifier and calibrator.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Test data.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
NDArray of shape (n_samples, n_classes)
|
The calibrated score for each max score and zeros at every other position in that line. |
Source code in mapie/calibration.py
predict
¶
Predict the class of the estimator after calibration. Note that in the top-label setting, this class does not change.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Test data.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
NDArray of shape (n_samples,)
|
The class from the scores. |
Source code in mapie/calibration.py
mapie.calibration.VennAbersCalibrator
¶
VennAbersCalibrator(
estimator: Optional[ClassifierMixin] = None,
cv: Optional[str] = None,
inductive: bool = True,
n_splits: Optional[int] = None,
train_proper_size: Optional[float] = None,
random_state: Optional[int] = None,
shuffle: bool = True,
stratify: Optional[ArrayLike] = None,
precision: Optional[int] = None,
cv_ensemble: bool = True,
)
Bases: BaseEstimator, ClassifierMixin
Venn-ABERS calibration for binary and multi-class problems.
A class implementing binary [1] or multi-class [2] Venn-ABERS calibration. This calibrator provides well-calibrated probabilities with validity guarantees. The implementation is based on the reference implementation by the user ip200 [3].
Can be used in 3 different forms: - Prefit Venn-ABERS: estimator is already fitted, only calibration is performed - Inductive Venn-ABERS (IVAP): splits data into training and calibration sets - Cross Venn-ABERS (CVAP): uses cross-validation for calibration
| PARAMETER | DESCRIPTION |
|---|---|
estimator
|
The classifier whose output needs to be calibrated to provide more
accurate
TYPE:
|
cv
|
The cross-validation strategy:
TYPE:
|
inductive
|
Determines the calibration strategy when
TYPE:
|
n_splits
|
Number of folds for Cross Venn-ABERS (CVAP). Must be at least 2.
Only used when
TYPE:
|
train_proper_size
|
Proportion of the dataset to use for proper training in Inductive
Venn-ABERS (IVAP). Only used when
TYPE:
|
random_state
|
Controls the shuffling applied to the data before splitting.
Pass an int for reproducible output across multiple function calls.
Can be overridden in the
TYPE:
|
shuffle
|
Whether to shuffle the data before splitting.
Can be overridden in the
TYPE:
|
stratify
|
For Inductive Venn-ABERS (IVAP) only. If not
TYPE:
|
precision
|
Number of decimal points to round Venn-ABERS calibration probabilities. Yields significantly faster computation for larger calibration datasets. Trade-off between speed and precision.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
classes_ |
Array with the name of each class.
TYPE:
|
n_classes_ |
Number of classes in the training dataset.
TYPE:
|
n_features_in_ |
Number of features seen during fit.
TYPE:
|
va_calibrator_ |
The fitted Venn-ABERS calibrator instance. May be None in prefit mode with multi-class classification.
TYPE:
|
transformers_ |
Transformers from sklearn pipeline to transform categorical attributes.
TYPE:
|
single_estimator_ |
The fitted estimator (only for prefit mode).
TYPE:
|
p_cal_ |
Calibration probabilities (only for prefit mode with multi-class).
TYPE:
|
y_cal_ |
Calibration labels (only for prefit mode with multi-class).
TYPE:
|
cv_ensemble |
If False then the predictions for the test set are generated using the underlying classifier trained on the whole training set, instead of on the split (in the case of IVAP) or folds (in the case of CVAP)
TYPE:
|
References
[1] Vovk, Vladimir, Ivan Petej, and Valentina Fedorova. "Large-scale probabilistic predictors with and without guarantees of validity." Advances in Neural Information Processing Systems 28 (2015). https://arxiv.org/pdf/1511.00213.pdf
[2] Manokhin, Valery. "Multi-class probabilistic classification using inductive and cross Venn–Abers predictors." In Conformal and Probabilistic Prediction and Applications, pp. 228-240. PMLR, 2017.
[3] Reference implementation: https://github.com/ip200/venn-abers/blob/main/src/venn_abers.py
Examples:
>>> import warnings
>>> warnings.filterwarnings("ignore")
>>> import numpy as np
>>> from sklearn.datasets import make_classification
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.naive_bayes import GaussianNB
>>> from mapie.calibration import VennAbersCalibrator
Example 1: Prefit mode
>>> X, y = make_classification(n_samples=1000, n_features=20,
... n_classes=3, n_informative=10,
... random_state=42)
>>> X_train, X_test, y_train, y_test = train_test_split(
... X, y, test_size=0.2, random_state=42
... )
>>> # Fit the base classifier
>>> clf = GaussianNB()
>>> _ = clf.fit(X_train, y_train)
>>> # Calibrate using prefit mode
>>> va_cal = VennAbersCalibrator(estimator=clf, cv="prefit")
>>> _ = va_cal.fit(X_test, y_test) # Use test set for calibration
>>> # Get calibrated probabilities
>>> calibrated_probs = va_cal.predict_proba(X_test)
Example 2: Inductive Venn-ABERS (IVAP)
>>> X, y = make_classification(n_samples=1000, n_features=20,
... n_classes=2, random_state=42)
>>> X_train, X_test, y_train, y_test = train_test_split(
... X, y, test_size=0.2, random_state=42
... )
>>> # Inductive mode with 30% calibration split
>>> clf = GaussianNB()
>>> va_cal = VennAbersCalibrator(
... estimator=clf,
... inductive=True,
... random_state=42
... )
>>> _ = va_cal.fit(X_train, y_train)
>>> calibrated_probs = va_cal.predict_proba(X_test)
>>> predictions = va_cal.predict(X_test)
Example 3: Cross Venn-ABERS (CVAP)
>>> X, y = make_classification(n_samples=1000, n_features=20,
... n_informative=10, n_classes=3,
... random_state=42)
>>> X_train, X_test, y_train, y_test = train_test_split(
... X, y, test_size=0.2, random_state=42
... )
>>> # Cross validation mode with 5 folds
>>> clf = GaussianNB()
>>> va_cal = VennAbersCalibrator(
... estimator=clf,
... inductive=False,
... n_splits=5,
... random_state=42
... )
>>> _ = va_cal.fit(X_train, y_train)
>>> calibrated_probs = va_cal.predict_proba(X_test)
>>> predictions = va_cal.predict(X_test)
Notes
- Venn-ABERS calibration provides probabilistic predictions with validity guarantees under the exchangeability assumption.
- For binary classification, the method produces well-calibrated probabilities with minimal assumptions.
- For multi-class problems, the method uses a one-vs-one approach to extend binary Venn-ABERS to multiple classes.
- The
precisionparameter can significantly speed up computation for large datasets with minimal impact on calibration quality. - When using
cv="prefit", ensure the estimator is fitted on a different dataset than the one used for calibration to avoid overfitting.
See Also
TopLabelCalibrator : Top-label calibration for multi-class problems. sklearn.calibration.CalibratedClassifierCV : Scikit-learn's probability calibration with isotonic regression or Platt scaling.
Source code in mapie/calibration.py
fit
¶
fit(
X: ArrayLike,
y: ArrayLike,
sample_weight: Optional[NDArray] = None,
calib_size: Optional[float] = 0.33,
random_state: Optional[
Union[int, RandomState, None]
] = None,
shuffle: Optional[bool] = True,
stratify: Optional[ArrayLike] = None,
**fit_params,
) -> "VennAbersCalibrator"
Fits the Venn-ABERS calibrator.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Training data.
TYPE:
|
y
|
Training labels.
TYPE:
|
sample_weight
|
Sample weights for fitting the out-of-fold models.
If
TYPE:
|
calib_size
|
Proportion of the dataset to use for calibration when using
Inductive Venn-ABERS (IVAP) mode (
TYPE:
|
random_state
|
Controls the shuffling applied to the data before applying the split. Pass an int for reproducible output across multiple function calls.
TYPE:
|
shuffle
|
Whether to shuffle the data before splitting. If shuffle=False then stratify must be None.
TYPE:
|
stratify
|
If not None, data is split in a stratified fashion, using this as the class labels.
TYPE:
|
**fit_params
|
Additional parameters for the underlying estimator.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
VennAbersCalibrator
|
The fitted calibrator. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If required parameters are missing for the chosen mode. |
Source code in mapie/calibration.py
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 | |
predict_proba
¶
predict_proba(
X: ArrayLike,
loss: str = "log",
p0_p1_output: bool = False,
) -> Union[
NDArray, Tuple[NDArray, Union[NDArray, list[NDArray]]]
]
Prediction of the calibrated scores using fitted classifier and Venn-ABERS calibrator.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Test data.
TYPE:
|
loss
|
Log or Brier loss function. Only used in inductive/cross-validation mode. For further details see Section 4 in https://arxiv.org/pdf/1511.00213.pdf
TYPE:
|
p0_p1_output
|
If True, also returns
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
NDArray of shape (n_samples, n_classes)
|
Venn-ABERS calibrated probabilities. |
p0_p1
|
Venn-ABERS calibrated p0 and p1 outputs when
TYPE:
|
Source code in mapie/calibration.py
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 | |
predict
¶
Predict the class of the estimator after Venn-ABERS calibration.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Test data.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
NDArray of shape (n_samples,)
|
The predicted class labels. |