API Reference¶
- class khalib.KhalibClassifier(estimator=None, train_size=0.75, random_state=None)¶
Bases:
ClassifierMixin,MetaEstimatorMixin,BaseEstimatorClassifier calibration via Khiops.
Calibrates classifier probabilities or decision scores using Khiops regularized histograms (MODL).
For binary classifiers, fits a Khiops histogram on the positive-class scores and maps each score to the positive-class probability of its bin.
For multiclass classifiers, fits a one-vs-rest Khiops histogram per class, applies binary calibration to each class score, and normalizes the resulting probabilities to sum to one.
Follows the
CalibratedClassifierCVinterface without cross-validation, because MODL histograms are regularized.- Parameters:
- estimatorestimator instance, default=None
Classifier whose outputs are calibrated for
predict_proba. IfNone, trains a KhiopsClassifier. If unfitted, fits a clone ontrain_sizesamples. If already fitted, copies the estimator for calibration.- train_sizefloat or int, default=0.75
Training-split size passed to
train_test_split. Used only whenestimatorisNoneor unfitted.- random_stateint, RandomState instance or None, default=None
Random seed passed to
train_test_split. Used only whenestimatorisNoneor unfitted.
- Attributes:
- fitted_estimator_
Independent fitted classifier used for calibration; an instance of KhiopsClassifier when
estimatorisNone.- histograms_list of size 1 or n_classes
For binary classification, a single-element list with the positive-class
Histogram. For multiclass classification, a list ofn_classesone-vs-restHistograminstances.classes_ndarray of shape (n_classes,)Class labels in probability column order.
- fit(X, y)¶
Fits the calibrated model.
- Parameters:
- Xarray-like of shape (n_samples, n_features)
Training features (or calibration features when
estimatoris already fitted).- yarray-like of shape (n_samples,)
Target class labels.
- Returns:
- self
Fitted estimator instance.
- Raises:
- ValueError
If inputs violate the Input requirements, calibration labels do not match the estimator’s classes, or multiclass decision scores use an unsupported layout.
- TypeError
random_stateis a boolean.
Notes
Calibration requirements
Calibration labels must contain at least two classes and exactly match the fitted estimator’s classes. Features can be sparse, unlike scores and labels. Multiclass decision scores must not use
decision_function_shape="ovo", including inside pipelines or searches.Fitted state
Fitted attributes are updated only after calibration succeeds; a failed refit preserves the previous fitted state. The supplied estimator is cloned before fitting, or copied if already fitted, isolating this classifier from later changes to it.
- property classes_¶
Class labels in probability column order.
- predict(X)¶
Predicts class labels from calibrated probabilities.
- Parameters:
- Xarray-like of shape (n_samples, n_features)
Input features.
- Returns:
- yndarray of shape (n_samples,)
Predicted class labels.
- predict_proba(X)¶
Estimates calibrated class probabilities.
- Parameters:
- Xarray-like of shape (n_samples, n_features)
Input features.
- Returns:
- Parray-like of shape (n_samples, n_classes)
Estimated calibrated probabilities per class.
- Raises:
- ValueError
If features or scores violate the Input requirements, multiclass decision scores use an unsupported layout, or zero-sum calibrated probabilities have no valid fallback.
- Warns:
- UserWarning
If multiclass calibrated probabilities sum to zero. Uncalibrated probabilities are returned for those samples instead.
Notes
Score layout
Multiclass decision scores must not use
decision_function_shape="ovo", including inside pipelines or searches. Features can be sparse.Zero-sum probabilities
If all calibrated class probabilities for a sample are zero, the fitted estimator must provide finite, nonnegative
predict_probavalues summing to one, which are used for the affected samples.
- get_metadata_routing()¶
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
- Returns:
- routingMetadataRequest
A
MetadataRequestencapsulating routing information.
- get_params(deep=True)¶
Get parameters for this estimator.
- Parameters:
- deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators.
- Returns:
- paramsdict
Parameter names mapped to their values.
- score(X, y, sample_weight=None)¶
Return accuracy on provided data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
- Parameters:
- Xarray-like of shape (n_samples, n_features)
Test samples.
- yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for
X.- sample_weightarray-like of shape (n_samples,), default=None
Sample weights.
- Returns:
- scorefloat
Mean accuracy of
self.predict(X)w.r.t.y.
- set_params(**params)¶
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as
Pipeline). The latter have parameters of the form<component>__<parameter>so that it’s possible to update each component of a nested object.- Parameters:
- **paramsdict
Estimator parameters.
- Returns:
- selfestimator instance
Estimator instance.
- khalib.calibration_error(y_scores, y, method: str = 'label-bin', histogram_method: str = 'khiops', max_bins: int = 0, multi_class_method: str = 'top-label', *, correction: str = 'v-ece', n_splits: int = 5, random_state=0)¶
Estimates calibration error via binning.
By default, uses cross-validated V-ECE with
method="label-bin". Setcorrection="none"to use the in-sample ECE estimators. The default binning method"khiops"builds a regularized histogram with pure target distributions per bin.- Parameters:
- y_scoresarray-like of shape (n_samples,) or (n_samples, n_classes)
Scores or probabilities. For binary ECE, the positive class is the second distinct label in sorted order; for two-column binary scores, column 1 contains scores for that class, and single-column binary scores are also accepted. For multiclass scores, columns correspond to the numerical or lexicographical order of the labels in
y, with every class present iny.- yarray-like of shape (n_samples,) or (n_samples, 1)
Target class labels.
- method{“label-bin”, “bin”}, default=”label-bin”
ECE estimation method. With
correction="v-ece", selects either a sample-wise label-bin direction or a uniform bin-level direction.- multi_class_method{“top-label”, “classwise”}, default=”top-label”
Multiclass ECE estimation method:
“top-label”: Estimates ECE on the predicted-class confidence scores. Ties select the first maximal score column.
“classwise”: Estimates one-vs-rest ECE per class and averages them weighted by class prevalence in
y.
- histogram_method{“khiops”, “eq-freq”, “eq-width”}, default=”khiops”
Histogram method:
“khiops”: Non-parametric regularized histogram method (MODL) that partitions scores so the target distribution is constant within each bin.
“eq-freq”: Equal-frequency quantile bins, with boundaries midway between adjacent distinct scores. Tied scores stay in the same bin, so bin counts can differ.
“eq-width”: Equal-width bins.
For “eq-freq” and “eq-width”,
ydoes not affect bin boundaries.- max_binsint, default=0
Upper bound on the number of bins; fewer bins are created when the data or regularization supports fewer splits.
0means:For “khiops”: no limit on the number of bins.
For “eq-freq” or “eq-width”: a maximum of 10 bins.
- correction{“none”, “v-ece”}, default=”v-ece”
Selects the in-sample ECE estimator (
"none") or the cross-fitted V-ECE heuristic ("v-ece"), which estimates directions from fold-specific training histograms.- n_splitsint, default=5
Number of shuffled, unstratified folds used by V-ECE.
- random_stateint, RandomState instance or None, default=0
Random seed used to shuffle V-ECE folds.
- Raises:
- ValueError
If inputs violate the Input requirements or the input requirements described in Notes.
- TypeError
random_stateis a boolean.
Notes
Input requirements
Top-label ECE requires both correct and incorrect predictions, and classwise ECE requires both positive and negative examples per class. With
correction="v-ece", scores must lie in [0, 1],multi_class_methodmust be"top-label", andn_splitsmust be an integer in[2, n_samples]. See Input requirements for common score, label, and option rules.In-sample ECE
The in-sample estimators described in [RCSM22] approximate the theoretical calibration error:
\[\mathbb{E}\left[ \left| \mathbb{P}\left[ Y = 1 | S \right] - S \right| \right]\]where \((S, Y)\) is a random vector in \([0, 1] \times \lbrace{0, 1\rbrace}\), \(S\) represents the normalized classifier score, and \(Y\) is the target.
Let \(\lbrace {B_i} \rbrace _{i=1}^I\) be a binning of \([0,1]\) and \(\lbrace (s_n, y_n) \rbrace_{n=1}^N\) be a sample drawn from \((S, Y)\).
The label-bin ECE estimator is:
\[\text{ECE}_{\text{lb}} = \frac{1}{N} \sum_{n=1}^N \sum_{i = 1}^I \mathbb{1}_{s_n \in B_i} \left| s_n - \bar{y_i} \right|\]where \(\bar{y_i}\) is the sample mean of \(Y\) in bin \(B_i\):
\[\frac{\sum_{n=1}^N \mathbb{1}_{s_n \in B_i} \cdot y_n}{|B_i|}.\]The bin ECE estimator is:
\[\text{ECE}_{\text{bin}} = \sum_{i = 1}^I \frac{\left| B_i \right| }{N} \left| \bar{s_i} - \bar{y_i} \right|\]where \(\bar{y_i}\) is as above, and \(\bar{s_i}\) is the sample mean of \(S\) in bin \(B_i\):
\[\frac{\sum_{n=1}^N \mathbb{1}_{s_n \in B_i} \cdot s_n}{|B_i|}.\]The bin estimator is a lower bound on the true ECE for any binning, and a lower bound on the label-bin estimator for a fixed binning.
Cross-validated V-ECE
The cross-validated V-ECE variant [BBBJH26] estimates directions from fold-specific training histograms. For fold \(m\), let \(\mathcal{F}_m\) denote its held-out samples, and let \(\bar{y}_{i,-m}\) and \(\bar{s}_{i,-m}\) be the training-complement label and score means in bin \(B_i\) of that fold’s histogram.
The label-bin V-ECE compares each held-out score with its training-bin label mean:
\[\text{V-ECE}_{\text{lb}} = \max\left(0, \frac{1}{N} \sum_m \sum_{n \in \mathcal{F}_m} \sum_{i=1}^{I_{-m}} \mathbb{1}_{s_n \in B_i} \operatorname{sign}(s_n-\bar{y}_{i,-m})(s_n-y_n)\right).\]The bin V-ECE applies the direction from the training-bin mean score and label to every held-out sample in the bin:
\[\text{V-ECE}_{\text{bin}} = \max\left(0, \frac{1}{N} \sum_m \sum_{n \in \mathcal{F}_m} \sum_{i=1}^{I_{-m}} \mathbb{1}_{s_n \in B_i} \operatorname{sign}(\bar{s}_{i,-m}-\bar{y}_{i,-m})(s_n-y_n)\right).\]The direction is zero for an empty training bin.
Cross-fitting makes the signed projection unbiased before zero clipping [BBBJH26]. Evaluating both directions and residuals on the full sample without fold splitting recovers the in-sample estimators.
Default parameters
The default configuration is V-ECE with label-bin error estimation and khiops binning:
V-ECE has an unbiased signed estimate before zero clipping and is more accurate when CE is small, where in-sample estimators perform poorly. The trade-off is lower accuracy overall and greater computational cost.
label-bin is exact when the conditional probability \(\mathbb{P}\left[ Y = 1 | S = s\right]\) is piecewise constant in \(s\). The bin method is systematically biased in this case.
khiops binning produces a conditional-probability estimate that converges to the ground truth as the sample size grows.
- khalib.build_reliability_diagram(y_scores, y, dirac_threshold=1e-06, log_plot_threshold=3.0, min_density_bar_width=0.0025)¶
Builds a reliability diagram with the score distribution below.
Builds the reliability diagram from a Khiops supervised histogram and the score distribution from a Khiops unsupervised histogram. Detects Dirac point-mass score distributions from the unsupervised histogram and adapts the score plot accordingly.
- Parameters:
- y_scoresarray-like of shape (n_samples,) or (n_samples, 1) or (n_samples, 2)
Positive-class scores or probabilities in [0, 1]. For a two-column array, column 1 is used; a single-column array is flattened.
- yarray-like of shape (n_samples,) or (n_samples, 1)
Target values containing two distinct class labels.
- dirac_thresholdfloat, default=1.0e-06
Isolated nonempty bins in the unsupervised score histogram narrower than
dirac_thresholdare treated as Dirac point masses.- log_plot_thresholdfloat, default=3.0
Density plot only: Uses a logarithmic y-axis when the base-10 log difference between the maximum and minimum positive densities exceeds
log_plot_threshold.- min_density_bar_widthfloat, default=2.5e-03
Density plot only: Plots bins narrower than
min_density_bar_widthwith widthmin_density_bar_width.
- Returns:
- tuple
2-tuple containing:
A
dictof twomatplotlib.axes.Axeskeyed by"reliability_diagram"and"score_distribution".
- Raises:
- ValueError
If inputs violate the Input requirements, scores fall outside [0, 1], labels are not binary, sample counts differ, or plotting thresholds are invalid.
- TypeError
A plotting threshold is not a real number.
Notes
Input requirements
All score columns must contain values in [0, 1], including unused columns. Labels must contain two distinct classes and match the score sample count. Plotting thresholds must be finite, positive real numbers, not booleans. See Input requirements for common score and label rules.
Figure lifecycle
The figure remains open on success and is closed if construction fails after creating the base plot.
- class khalib.Histogram(breakpoints: list[float], freqs: list[int], target_freqs: list[tuple] = <factory>, classes: list = <factory>)¶
Bases:
objectA histogram with optional target variable statistics.
Note
Use the factory method
from_datarather than the constructor to build histograms from data.- Attributes:
- breakpointslist[float]
Strictly increasing bin breakpoints.
- freqslist of float
Finite, nonnegative bin frequencies.
- densitieslist[float]
Bin densities.
- classeslist
Class labels.
- target_freqslist[tuple], optional
Finite, nonnegative target frequencies per bin. Each tuple has the same length as
classes.- target_probaslist[tuple], optional
Target conditional probabilities per bin, in class order.
- Raises:
- ValueError
If fields violate the Input requirements, have inconsistent dimensions, or target frequencies do not sum to their bin frequency.
Notes
Integer precision
NumPy integer endpoints are stored as Python integers to avoid fixed-width overflow. Integer scores and endpoints retain exact comparisons during lookup.
Density limits
Positive infinite densities caused by overflow are capped at the largest finite float. For capped bins, density times bin width no longer equals the bin’s probability mass. Widths exceeding the floating-point range are scaled to preserve representable densities.
- classmethod from_data(x, y=None, method: str = 'khiops', max_bins: int = 0, use_finest: bool = False) Histogram¶
Computes a histogram of a 1-D vector.
- Parameters:
- xarray-like of shape (n_samples,) or (n_samples, 1)
Input scores.
- yarray-like of shape (n_samples,) or (n_samples, 1), optional
Target values.
- method{“khiops”, “eq-freq”, “eq-width”}, default=”khiops”
Histogram method:
“khiops”: Non-parametric regularized histogram method (MODL).
“eq-freq”: Equal-frequency quantile bins, with boundaries midway between adjacent distinct scores. Tied scores stay in the same bin, so bin counts can differ.
“eq-width”: Equal-width bins.
For “eq-freq” and “eq-width”,
ydoes not affect bin boundaries.- max_binsint, default=0
Upper bound on the number of bins; fewer bins are created when the data or regularization supports fewer splits.
0means:For “khiops”: no limit on the number of bins.
For “eq-freq” or “eq-width”: a maximum of 10 bins.
- use_finestbool, default=False
Unsupervised ‘khiops’ histogram only: If
True, builds the finest histogram instead of the most interpretable one. If no histogram has an information rate of 100, uses the last histogram.
- Returns:
HistogramHistogram containing the bin edges and frequencies.
- Raises:
- ValueError
If scores, labels, or max_bins violate the Input requirements, scores are empty, sample counts differ, or method is unsupported.
- TypeError
use_finestis not a boolean.
- classmethod from_data_and_breakpoints(x, breakpoints: list[float], y=None) Histogram¶
Builds a histogram from breakpoints and data.
- Parameters:
- xarray-like of shape (n_samples,) or (n_samples, 1)
Values to discretize.
- breakpointslist[float]
Strictly increasing bin edges.
- yarray-like of shape (n_samples,) or (n_samples, 1), optional
Target values corresponding to
x.
- Raises:
- ValueError
If scores, labels, or breakpoints violate the Input requirements, scores are empty, or sample counts differ.
- find(value: float) int¶
Returns the histogram bin index for a scalar value.
- Parameters:
- valuefloat
Value to look up in the histogram bins.
- Returns:
- int
Index of the bin containing
value.
- Raises:
- ValueError
If value violates the score Input requirements or is not scalar.
- vfind(values)¶
Returns the histogram bin indexes for an array of values.
- Parameters:
- valuesarray-like
Values to look up in the histogram bins.
- Returns:
- array-like
Indexes of the bins containing
values.
- Raises:
- ValueError
If values violate the score Input requirements.
- khalib.calibrate_binary(y_scores, histogram: Histogram, only_positive: bool = False)¶
Calibrates binary scores with a histogram.
Calibrates binary classification scores directly without fitting a
KhalibClassifierestimator.- Parameters:
- y_scoresarray-like of shape (n_samples,) or (n_samples, 1)
Scores for the second class in
histogram.classes.- histogram
Histogram Binary histogram with target statistics. Its class order defines the output probability-column order; the second class is positive.
- only_positivebool, default=False
If
True, returns a 1-D array of positive-class probabilities; otherwise returns a 2-D array of probabilities for both classes.
- Raises:
- ValueError
If scores violate the Input requirements, the histogram lacks binary target statistics, or scores map to empty bins.
- TypeError
only_positiveis not a boolean.
Notes
Input requirements
The histogram must have target frequencies for two classes. Empty score arrays are accepted. See Input requirements for common score rules.
Bin lookup
Finite scores outside the histogram range map to the nearest end bin. Scores mapping to empty bins are rejected.
References
Roelofs, R., Cain, N., Shlens, J. & Mozer, M.C.. (2022). Mitigating Bias in Calibration Error Estimation . <i>Proceedings of The 25th International Conference on Artificial Intelligence and Statistics</i>, in <i>Proceedings of Machine Learning Research</i> 151:4036-4054 Available from https://proceedings.mlr.press/v151/roelofs22a.html.
Berta, E., Braun, S., Bach, F., Jordan, M.I. & Holzmüller, D. (2026). V-ECE: Estimating General Expected Calibration Errors. https://arxiv.org/abs/2602.24230.