calibration-proba 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. calibration_proba-0.1.0/LICENSE +21 -0
  2. calibration_proba-0.1.0/PKG-INFO +95 -0
  3. calibration_proba-0.1.0/README.md +68 -0
  4. calibration_proba-0.1.0/calibration_proba/__init__.py +37 -0
  5. calibration_proba-0.1.0/calibration_proba/_calibrators/__init__.py +1 -0
  6. calibration_proba-0.1.0/calibration_proba/_calibrators/_temperature.py +34 -0
  7. calibration_proba-0.1.0/calibration_proba/_calibrators/binary/__init__.py +15 -0
  8. calibration_proba-0.1.0/calibration_proba/_calibrators/binary/_common.py +58 -0
  9. calibration_proba-0.1.0/calibration_proba/_calibrators/binary/isotonic.py +288 -0
  10. calibration_proba-0.1.0/calibration_proba/_calibrators/binary/isotonic_linear.py +354 -0
  11. calibration_proba-0.1.0/calibration_proba/_calibrators/binary/sigmoid.py +228 -0
  12. calibration_proba-0.1.0/calibration_proba/_calibrators/binary/temperature.py +60 -0
  13. calibration_proba-0.1.0/calibration_proba/_calibrators/multiclass/__init__.py +11 -0
  14. calibration_proba-0.1.0/calibration_proba/_calibrators/multiclass/_common.py +21 -0
  15. calibration_proba-0.1.0/calibration_proba/_calibrators/multiclass/shared.py +161 -0
  16. calibration_proba-0.1.0/calibration_proba/_calibrators/multiclass/temperature.py +76 -0
  17. calibration_proba-0.1.0/calibration_proba/_plotting/__init__.py +1 -0
  18. calibration_proba-0.1.0/calibration_proba/_plotting/_common.py +135 -0
  19. calibration_proba-0.1.0/calibration_proba/_plotting/mapping.py +292 -0
  20. calibration_proba-0.1.0/calibration_proba/_plotting/reliability.py +407 -0
  21. calibration_proba-0.1.0/calibration_proba/base.py +309 -0
  22. calibration_proba-0.1.0/calibration_proba/prob_calib.py +606 -0
  23. calibration_proba-0.1.0/calibration_proba.egg-info/PKG-INFO +95 -0
  24. calibration_proba-0.1.0/calibration_proba.egg-info/SOURCES.txt +32 -0
  25. calibration_proba-0.1.0/calibration_proba.egg-info/dependency_links.txt +1 -0
  26. calibration_proba-0.1.0/calibration_proba.egg-info/requires.txt +6 -0
  27. calibration_proba-0.1.0/calibration_proba.egg-info/top_level.txt +1 -0
  28. calibration_proba-0.1.0/pyproject.toml +42 -0
  29. calibration_proba-0.1.0/setup.cfg +4 -0
  30. calibration_proba-0.1.0/tests/test_base.py +97 -0
  31. calibration_proba-0.1.0/tests/test_binary.py +741 -0
  32. calibration_proba-0.1.0/tests/test_multiclass.py +336 -0
  33. calibration_proba-0.1.0/tests/test_plots.py +439 -0
  34. calibration_proba-0.1.0/tests/test_prob_calib.py +607 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Maksim Tyurikov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: calibration-proba
3
+ Version: 0.1.0
4
+ Summary: Probability calibration for binary and multiclass models with a scikit-learn style API.
5
+ Author: Maksim Tyurikov
6
+ License-Expression: MIT
7
+ Keywords: probability-calibration,calibration,binary-classification,multiclass-classification,machine-learning
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: numpy>=1.21
22
+ Requires-Dist: scipy>=1.12
23
+ Requires-Dist: matplotlib>=3.6
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest>=7.0; extra == "test"
26
+ Dynamic: license-file
27
+
28
+ # calibration_proba
29
+
30
+ Calibrate predicted probabilities for binary and multiclass classifiers with
31
+ `ProbCalib`.
32
+
33
+ - **Binary** (`task="binary"`)
34
+ - `isotonic_linear` (default)
35
+ - `isotonic`
36
+ - `sigmoid`
37
+ - `temperature_scaling`
38
+ - **Multiclass** (`task="multiclass"`)
39
+ - `temperature_scaling` (default)
40
+ - `sigmoid`
41
+ - `isotonic_linear`
42
+
43
+ ## Installation
44
+
45
+ ```bash
46
+ pip install calibration-proba
47
+ ```
48
+
49
+ ## Calibrate probabilities
50
+
51
+ Fit the calibrator on a separate calibration set, then apply it to the test
52
+ predictions. This binary example uses the predicted probability of class 1.
53
+
54
+ ```python
55
+ from calibration_proba import ProbCalib
56
+
57
+ p_cal = model.predict_proba(X_cal)[:, 1]
58
+ p_test = model.predict_proba(X_test)[:, 1]
59
+
60
+ calib = ProbCalib(task="binary", method="isotonic_linear", max_bins=10)
61
+ calib.fit(p_cal, y_cal)
62
+ p_calibrated = calib.predict(p_test)
63
+
64
+ calib.save_model("calibrator.npz")
65
+ calib = ProbCalib.load_model("calibrator.npz")
66
+ ```
67
+
68
+ ## Plot the mapping and reliability diagram
69
+
70
+ ```python
71
+ from calibration_proba import plot_calibration_curve
72
+
73
+ mapping = calib.plot()
74
+ reliability = plot_calibration_curve(y_test, p_calibrated)
75
+
76
+ mapping.savefig("mapping.png", dpi=180)
77
+ reliability.savefig("reliability.png", dpi=180)
78
+ ```
79
+
80
+ | Fitted calibration mapping | Reliability diagram |
81
+ | --- | --- |
82
+ | [![Fitted calibration mapping](https://raw.githubusercontent.com/maks371/calibration-proba/main/examples/binary_mapping_isotonic_linear.png)](https://raw.githubusercontent.com/maks371/calibration-proba/main/examples/binary_mapping_isotonic_linear.png) | [![Reliability diagram](https://raw.githubusercontent.com/maks371/calibration-proba/main/examples/binary_reliability.png)](https://raw.githubusercontent.com/maks371/calibration-proba/main/examples/binary_reliability.png) |
83
+
84
+ ## Benchmark on Adult with CatBoost
85
+
86
+ ECE before calibration was **0.0098**. The table shows changes on the test
87
+ set relative to the uncalibrated predictions. Both isotonic methods use
88
+ `max_bins=None`. See the [full benchmark report](https://github.com/maks371/calibration-proba/blob/main/experiments/calibration_benchmark/results.md#adult).
89
+
90
+ | Method | Δ ECE | Δ ECE (%) | Δ ROC AUC |
91
+ | --- | ---: | ---: | ---: |
92
+ | `isotonic_linear` | **-0.0047** | -47.75% | 0 |
93
+ | `isotonic` | -0.0041 | -42.04% | -0.00035 |
94
+ | `sigmoid` | -0.0002 | -2.51% | 0 |
95
+ | `temperature_scaling` | +0.0008 | +7.92% | 0 |
@@ -0,0 +1,68 @@
1
+ # calibration_proba
2
+
3
+ Calibrate predicted probabilities for binary and multiclass classifiers with
4
+ `ProbCalib`.
5
+
6
+ - **Binary** (`task="binary"`)
7
+ - `isotonic_linear` (default)
8
+ - `isotonic`
9
+ - `sigmoid`
10
+ - `temperature_scaling`
11
+ - **Multiclass** (`task="multiclass"`)
12
+ - `temperature_scaling` (default)
13
+ - `sigmoid`
14
+ - `isotonic_linear`
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pip install calibration-proba
20
+ ```
21
+
22
+ ## Calibrate probabilities
23
+
24
+ Fit the calibrator on a separate calibration set, then apply it to the test
25
+ predictions. This binary example uses the predicted probability of class 1.
26
+
27
+ ```python
28
+ from calibration_proba import ProbCalib
29
+
30
+ p_cal = model.predict_proba(X_cal)[:, 1]
31
+ p_test = model.predict_proba(X_test)[:, 1]
32
+
33
+ calib = ProbCalib(task="binary", method="isotonic_linear", max_bins=10)
34
+ calib.fit(p_cal, y_cal)
35
+ p_calibrated = calib.predict(p_test)
36
+
37
+ calib.save_model("calibrator.npz")
38
+ calib = ProbCalib.load_model("calibrator.npz")
39
+ ```
40
+
41
+ ## Plot the mapping and reliability diagram
42
+
43
+ ```python
44
+ from calibration_proba import plot_calibration_curve
45
+
46
+ mapping = calib.plot()
47
+ reliability = plot_calibration_curve(y_test, p_calibrated)
48
+
49
+ mapping.savefig("mapping.png", dpi=180)
50
+ reliability.savefig("reliability.png", dpi=180)
51
+ ```
52
+
53
+ | Fitted calibration mapping | Reliability diagram |
54
+ | --- | --- |
55
+ | [![Fitted calibration mapping](https://raw.githubusercontent.com/maks371/calibration-proba/main/examples/binary_mapping_isotonic_linear.png)](https://raw.githubusercontent.com/maks371/calibration-proba/main/examples/binary_mapping_isotonic_linear.png) | [![Reliability diagram](https://raw.githubusercontent.com/maks371/calibration-proba/main/examples/binary_reliability.png)](https://raw.githubusercontent.com/maks371/calibration-proba/main/examples/binary_reliability.png) |
56
+
57
+ ## Benchmark on Adult with CatBoost
58
+
59
+ ECE before calibration was **0.0098**. The table shows changes on the test
60
+ set relative to the uncalibrated predictions. Both isotonic methods use
61
+ `max_bins=None`. See the [full benchmark report](https://github.com/maks371/calibration-proba/blob/main/experiments/calibration_benchmark/results.md#adult).
62
+
63
+ | Method | Δ ECE | Δ ECE (%) | Δ ROC AUC |
64
+ | --- | ---: | ---: | ---: |
65
+ | `isotonic_linear` | **-0.0047** | -47.75% | 0 |
66
+ | `isotonic` | -0.0041 | -42.04% | -0.00035 |
67
+ | `sigmoid` | -0.0002 | -2.51% | 0 |
68
+ | `temperature_scaling` | +0.0008 | +7.92% | 0 |
@@ -0,0 +1,37 @@
1
+ """Calibration of predicted probabilities for binary and multiclass models."""
2
+
3
+ from ._calibrators.binary import (
4
+ BINARY_METHODS,
5
+ BinaryTemperatureScalingCalibrator,
6
+ IsotonicCalibrator,
7
+ IsotonicLinearCalibrator,
8
+ SigmoidCalibrator,
9
+ )
10
+ from ._calibrators.multiclass import (
11
+ MULTICLASS_METHODS,
12
+ SharedIsotonicLinearCalibrator,
13
+ SharedSigmoidCalibrator,
14
+ TemperatureScalingCalibrator,
15
+ )
16
+ from ._plotting.reliability import plot_calibration_curve
17
+ from .base import BaseCalibrator, NotFittedError
18
+ from .prob_calib import ProbCalib
19
+
20
+ __version__ = "0.1.0"
21
+
22
+ __all__ = [
23
+ "ProbCalib",
24
+ "plot_calibration_curve",
25
+ "BaseCalibrator",
26
+ "NotFittedError",
27
+ "IsotonicLinearCalibrator",
28
+ "SigmoidCalibrator",
29
+ "IsotonicCalibrator",
30
+ "BinaryTemperatureScalingCalibrator",
31
+ "TemperatureScalingCalibrator",
32
+ "SharedSigmoidCalibrator",
33
+ "SharedIsotonicLinearCalibrator",
34
+ "BINARY_METHODS",
35
+ "MULTICLASS_METHODS",
36
+ "__version__",
37
+ ]
@@ -0,0 +1 @@
1
+ """Implementations of binary and multiclass calibration methods."""
@@ -0,0 +1,34 @@
1
+ """Bounded temperature selection shared by binary and multiclass scaling."""
2
+
3
+ import warnings
4
+
5
+ import numpy as np
6
+ from scipy.optimize import minimize_scalar
7
+
8
+
9
+ _LOG_T_BOUNDS = (np.log(1e-2), np.log(1e2))
10
+ _MIN_NLL_GAIN = 1e-6
11
+
12
+
13
+ def _fit_temperature(loss):
14
+ """Return the selected temperature and the loss before and after scaling."""
15
+ result = minimize_scalar(
16
+ lambda log_temperature: loss(np.exp(log_temperature)),
17
+ bounds=_LOG_T_BOUNDS,
18
+ method="bounded",
19
+ options={"xatol": 1e-8},
20
+ )
21
+ before = loss(1.0)
22
+ temperature, after = 1.0, before
23
+ if before - result.fun > _MIN_NLL_GAIN:
24
+ temperature, after = float(np.exp(result.x)), result.fun
25
+ lower, upper = _LOG_T_BOUNDS
26
+ if min(result.x - lower, upper - result.x) < 1e-6:
27
+ warnings.warn(
28
+ f"the optimal temperature lies on the search boundary "
29
+ f"[{np.exp(lower):g}, {np.exp(upper):g}]; the fitted value "
30
+ f"{temperature:.4g} may be clipped",
31
+ RuntimeWarning,
32
+ stacklevel=3,
33
+ )
34
+ return temperature, before, after
@@ -0,0 +1,15 @@
1
+ """Binary calibration methods used by the public estimator."""
2
+
3
+ from .isotonic import IsotonicCalibrator
4
+ from .isotonic_linear import IsotonicLinearCalibrator
5
+ from .sigmoid import SigmoidCalibrator
6
+ from .temperature import BinaryTemperatureScalingCalibrator
7
+
8
+
9
+ #: available binary calibration methods: name -> calibrator class
10
+ BINARY_METHODS = {
11
+ "isotonic_linear": IsotonicLinearCalibrator,
12
+ "sigmoid": SigmoidCalibrator,
13
+ "isotonic": IsotonicCalibrator,
14
+ "temperature_scaling": BinaryTemperatureScalingCalibrator,
15
+ }
@@ -0,0 +1,58 @@
1
+ """Input checks and fitted score statistics for binary calibrators."""
2
+
3
+ import numpy as np
4
+
5
+ from ...base import (
6
+ BIN_POINTS,
7
+ _sorted_quantile,
8
+ calibration_bins,
9
+ check_binary_targets,
10
+ crowded_window,
11
+ to_1d_array,
12
+ )
13
+
14
+
15
+ def _check_pair(y_pred, y_true):
16
+ """Validate and align the inputs of a binary calibrator."""
17
+ scores = to_1d_array(y_pred, "y_pred")
18
+ targets = check_binary_targets(y_true)
19
+ if scores.shape != targets.shape:
20
+ raise ValueError(
21
+ f"y_pred and y_true must have the same length, "
22
+ f"got {scores.size} and {targets.size}"
23
+ )
24
+ return scores, targets
25
+
26
+
27
+ def _store_score_range(calibrator, scores, targets, order=None):
28
+ """Remember the training score range, dense-region quantiles, the
29
+ zoom-inset band and the observed 10-quantile-bin points so that
30
+ ``ProbCalib.plot`` can draw the fitted mapping on the trained domain.
31
+
32
+ Everything is read off the sorted scores. ``order`` is their stable
33
+ argsort, which the isotonic fits compute anyway; without it the scores
34
+ are sorted here and the targets keep their original order.
35
+
36
+ The band is stored in the model archive as a two-float array, with
37
+ NaNs marking its absence.
38
+ """
39
+ if order is None:
40
+ ordered = np.sort(scores)
41
+ bin_scores, bin_targets = scores, targets
42
+ else:
43
+ ordered = scores[order]
44
+ bin_scores, bin_targets = ordered, targets[order]
45
+ band = crowded_window(ordered)
46
+ zoom_band = (
47
+ np.array([np.nan, np.nan]) if band is None
48
+ else np.asarray(band, dtype=float)
49
+ )
50
+ inner = np.linspace(0.0, 1.0, BIN_POINTS + 1)[1:-1]
51
+ edges = np.unique([_sorted_quantile(ordered, q) for q in inner])
52
+ vars(calibrator).update(
53
+ score_min_=float(ordered[0]),
54
+ score_max_=float(ordered[-1]),
55
+ score_q90_=_sorted_quantile(ordered, 0.90),
56
+ score_zoom_band_=zoom_band,
57
+ bin_points_=calibration_bins(bin_scores, bin_targets, edges=edges),
58
+ )
@@ -0,0 +1,288 @@
1
+ """Isotonic calibration and block operations shared by the isotonic fits."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import heapq
6
+ from typing import NamedTuple, Optional
7
+
8
+ import numpy as np
9
+ from scipy.optimize import isotonic_regression
10
+
11
+ from ...base import BaseCalibrator, check_verbose, to_1d_array
12
+ from ._common import _check_pair, _store_score_range
13
+
14
+
15
+ class _ScoreAggregates(NamedTuple):
16
+ """Training scores sorted ascending and summed up per unique score."""
17
+
18
+ order: np.ndarray # stable argsort of the scores as they were given
19
+ unique_scores: np.ndarray # the distinct scores, ascending
20
+ counts: np.ndarray # observations behind each unique score
21
+ score_sums: np.ndarray # sum of the scores behind each unique score
22
+ target_sums: np.ndarray # sum of the targets behind each unique score
23
+
24
+
25
+ def _sort_and_aggregate(scores, targets) -> _ScoreAggregates:
26
+ """Sort by score and aggregate per unique score: the first step of every
27
+ isotonic fit, done once and shared by the fits and the plot statistics."""
28
+ order = np.argsort(scores, kind="stable")
29
+ sorted_scores = scores[order]
30
+ sorted_targets = targets[order]
31
+ unique_scores, first_idx = np.unique(sorted_scores, return_index=True)
32
+ return _ScoreAggregates(
33
+ order=order,
34
+ unique_scores=unique_scores,
35
+ counts=np.diff(np.append(first_idx, sorted_scores.size)).astype(float),
36
+ score_sums=np.add.reduceat(sorted_scores, first_idx),
37
+ target_sums=np.add.reduceat(sorted_targets, first_idx),
38
+ )
39
+
40
+
41
+ def _validate_bins(bins):
42
+ """Validate the initial interval edges of a binary isotonic fit."""
43
+ if bins is None:
44
+ return None
45
+ edges = np.asarray(bins)
46
+ if edges.ndim != 1 or edges.size < 2:
47
+ raise ValueError("bins must be a 1-D array with at least two edges")
48
+ edges = to_1d_array(edges, "bins")
49
+ if np.any(edges[1:] <= edges[:-1]):
50
+ raise ValueError("bins must be strictly increasing")
51
+ return edges.copy()
52
+
53
+
54
+ class IsotonicCalibrator(BaseCalibrator):
55
+ """Isotonic calibration: a non-decreasing step/linear interpolation.
56
+
57
+ Duplicate scores are aggregated, the monotone fit comes from the pool
58
+ adjacent violators algorithm as implemented by
59
+ :func:`scipy.optimize.isotonic_regression`, and prediction is a linear
60
+ interpolation between the fitted thresholds. Input scores in [0, 1]
61
+ outside the observed score range use the nearest fitted value.
62
+
63
+ When ``max_bins`` is set, the number of blocks (maximal runs of equal
64
+ value) of the monotone fit is capped: blocks are merged pairwise, each
65
+ fusion replacing the pair with its weighted average. Monotonicity is
66
+ preserved by construction, so only the choice of the pair matters.
67
+
68
+ Parameters
69
+ ----------
70
+ max_bins : int, optional
71
+ Maximum number of blocks in the fitted mapping. ``None`` (default)
72
+ keeps the unrestricted isotonic fit.
73
+ merge_rule : {"ward", "count"}, default="ward"
74
+ Which blocks to merge when the fit has more blocks than
75
+ ``max_bins``:
76
+
77
+ - ``"ward"`` — merge the adjacent pair whose fusion increases the
78
+ weighted squared error the least;
79
+ - ``"count"`` — merge the block with the fewest observations into
80
+ its lighter neighbour (ties resolved to the left).
81
+ verbose : {0, 1, 2}, default=0
82
+ Progress reporting: 0 is silent, 1 prints the fitted summary,
83
+ 2 additionally prints the block counts before and after merging.
84
+ bins : array-like or None, default=None
85
+ Strictly increasing interval edges in [0, 1] covering the training
86
+ scores. Right edges are included in their interval, and the first
87
+ interval includes its left edge. Empty intervals are skipped.
88
+ With custom bins, ``max_bins`` is ignored.
89
+ """
90
+
91
+ _fitted_attrs = ("X_thresholds_", "y_thresholds_")
92
+
93
+ def __init__(
94
+ self,
95
+ max_bins: Optional[int] = None,
96
+ merge_rule: str = "ward",
97
+ verbose: int = 0,
98
+ *,
99
+ bins=None,
100
+ ):
101
+ self.bins = _validate_bins(bins)
102
+ if self.bins is not None:
103
+ max_bins = None
104
+ if max_bins is not None and (
105
+ not isinstance(max_bins, (int, np.integer)) or max_bins < 1
106
+ ):
107
+ raise ValueError(
108
+ f"max_bins must be a positive integer or None, got {max_bins!r}"
109
+ )
110
+ if merge_rule not in ("ward", "count"):
111
+ raise ValueError(
112
+ f"merge_rule must be 'ward' or 'count', got {merge_rule!r}"
113
+ )
114
+ self.max_bins = max_bins
115
+ self.merge_rule = merge_rule
116
+ self.verbose = check_verbose(verbose)
117
+
118
+ def fit(self, y_pred, y_true):
119
+ scores, targets = _check_pair(y_pred, y_true)
120
+ data = _sort_and_aggregate(scores, targets)
121
+ self._log(
122
+ 2,
123
+ f"fitting on {scores.size} samples, score range "
124
+ f"[{data.unique_scores[0]:.4g}, {data.unique_scores[-1]:.4g}]",
125
+ )
126
+
127
+ block_values, _, spans, n_blocks = _isotonic_blocks(
128
+ data, self.max_bins, self.merge_rule, self.bins,
129
+ )
130
+ self._log(
131
+ 2,
132
+ f"{data.unique_scores.size} unique scores, {n_blocks} PAV blocks",
133
+ )
134
+ if n_blocks > block_values.size:
135
+ self._log(
136
+ 2,
137
+ f"merged down to {block_values.size} blocks "
138
+ f"(max_bins={self.max_bins})",
139
+ )
140
+ x_thresholds = data.unique_scores.astype(float)
141
+ y_thresholds = np.repeat(block_values, spans)
142
+ _store_score_range(self, scores, targets, data.order)
143
+ self.X_thresholds_, self.y_thresholds_ = x_thresholds, y_thresholds
144
+ self._log(1, f"fitted {block_values.size} blocks")
145
+ return self
146
+
147
+ def predict(self, y_pred):
148
+ self._check_fitted()
149
+ scores = to_1d_array(y_pred, "y_pred")
150
+ return np.interp(scores, self.X_thresholds_, self.y_thresholds_)
151
+
152
+
153
+ def _isotonic_blocks(data: _ScoreAggregates, max_blocks, merge_rule, bins=None):
154
+ """Blocks of the isotonic fit over the aggregated scores.
155
+
156
+ Returns block values, weights, spans in unique scores and the number of
157
+ blocks before any cap. Custom bins are pooled without a cap.
158
+ """
159
+ counts, target_sums = data.counts, data.target_sums
160
+ if bins is not None:
161
+ scores = data.unique_scores
162
+ if scores[0] < bins[0] or scores[-1] > bins[-1]:
163
+ raise ValueError("bins must cover the full range of training scores")
164
+ cuts = np.searchsorted(scores, bins[1:-1], side="right")
165
+ bounds = np.unique(np.r_[0, cuts, scores.size]) # skip empty bins
166
+ counts = np.add.reduceat(counts, bounds[:-1])
167
+ target_sums = np.add.reduceat(target_sums, bounds[:-1])
168
+
169
+ values, weights, spans = _pool_violator_blocks(target_sums / counts, counts)
170
+ n_blocks = values.size
171
+ if bins is not None:
172
+ # Convert spans in the initial bins back to spans in unique scores.
173
+ spans = np.diff(bounds[np.cumsum(spans)], prepend=0)
174
+ elif max_blocks is not None and n_blocks > max_blocks:
175
+ values, weights, spans = _merge_monotone_blocks(
176
+ values, weights, spans, max_blocks, merge_rule
177
+ )
178
+ return values, weights, spans, n_blocks
179
+
180
+
181
+ def _pool_violator_blocks(values, weights):
182
+ """Pool adjacent violators for the isotonic fit.
183
+
184
+ The fit comes from :func:`scipy.optimize.isotonic_regression`. Returns
185
+ ``(block_values, block_weights, spans)`` where ``spans[i]`` unique-x
186
+ points share the constant value ``block_values[i]`` and
187
+ ``block_weights[i]`` counts the observations behind that block. A block
188
+ is a maximal run of equal value: neighbours with the same value form one
189
+ block.
190
+ """
191
+ result = isotonic_regression(values, weights=weights)
192
+ return result.x[result.blocks[:-1]], result.weights, np.diff(result.blocks)
193
+
194
+
195
+ def _merge_monotone_blocks(values, weights, spans, max_blocks, merge_rule):
196
+ """Merge adjacent blocks of a monotone sequence until ``max_blocks`` remain.
197
+
198
+ Every fusion replaces a neighbouring pair with its weighted average,
199
+ which cannot break monotonicity of an already non-decreasing sequence, so
200
+ only the choice of the pair matters. Blocks live in doubly linked dicts;
201
+ stale heap entries are filtered through per-block version counters, which
202
+ keeps the whole merge at O(B log B).
203
+
204
+ ``merge_rule="ward"`` always fuses the pair with the smallest increase of
205
+ the weighted squared error,
206
+
207
+ cost(a, b) = w_a * w_b / (w_a + w_b) * (m_b - m_a) ** 2,
208
+
209
+ while ``merge_rule="count"`` fuses the lightest block into its lighter
210
+ neighbour. Ties are broken to the left in both rules.
211
+ """
212
+ if values.size <= max_blocks:
213
+ return values, weights, spans
214
+
215
+ block_value = {i: float(v) for i, v in enumerate(values)}
216
+ block_weight = {i: float(w) for i, w in enumerate(weights)}
217
+ block_span = {i: int(s) for i, s in enumerate(spans)}
218
+ n_blocks = values.size
219
+ left = {i: i - 1 for i in range(n_blocks)}
220
+ right = {i: i + 1 for i in range(n_blocks)}
221
+ left[0] = -1
222
+ right[n_blocks - 1] = -1
223
+ version = {i: 0 for i in range(n_blocks)}
224
+
225
+ def fuse(index, neighbour):
226
+ """Merge ``neighbour`` (right of ``index``) into ``index``."""
227
+ total = block_weight[index] + block_weight[neighbour]
228
+ block_value[index] = (
229
+ block_value[index] * block_weight[index]
230
+ + block_value[neighbour] * block_weight[neighbour]
231
+ ) / total
232
+ block_weight[index] = total
233
+ block_span[index] += block_span[neighbour]
234
+ after = right[neighbour]
235
+ right[index] = after
236
+ if after != -1:
237
+ left[after] = index
238
+ version[index] += 1
239
+ version[neighbour] += 1
240
+ del block_value[neighbour], block_weight[neighbour], block_span[neighbour]
241
+
242
+ if merge_rule == "ward":
243
+
244
+ def pair_cost(index):
245
+ neighbour = right[index]
246
+ w_a, w_b = block_weight[index], block_weight[neighbour]
247
+ return (w_a * w_b / (w_a + w_b)) * (
248
+ block_value[neighbour] - block_value[index]
249
+ ) ** 2
250
+
251
+ heap = [
252
+ (pair_cost(i), i, version[i], right[i], version[right[i]])
253
+ for i in range(n_blocks - 1)
254
+ ]
255
+ heapq.heapify(heap)
256
+ while len(block_value) > max_blocks:
257
+ _, index, ver, neighbour, ver_nb = heapq.heappop(heap)
258
+ if version.get(index) != ver or version.get(neighbour) != ver_nb:
259
+ continue # stale entry: one of the blocks has changed since
260
+ fuse(index, neighbour)
261
+ for a, b in ((left[index], index), (index, right[index])):
262
+ if a != -1 and b != -1:
263
+ heapq.heappush(heap, (pair_cost(a), a, version[a], b, version[b]))
264
+ else: # "count"
265
+ heap = [(block_weight[i], i, version[i]) for i in range(n_blocks)]
266
+ heapq.heapify(heap)
267
+ while len(block_value) > max_blocks:
268
+ _, index, ver = heapq.heappop(heap)
269
+ if version.get(index) != ver:
270
+ continue # stale entry: the block has changed since
271
+ neighbours = [nb for nb in (left[index], right[index]) if nb != -1]
272
+ partner = min(neighbours, key=lambda nb: (block_weight[nb], nb))
273
+ if partner < index:
274
+ fuse(partner, index) # the left block of the pair survives
275
+ survivor = partner
276
+ else:
277
+ fuse(index, partner)
278
+ survivor = index
279
+ heapq.heappush(
280
+ heap, (block_weight[survivor], survivor, version[survivor])
281
+ )
282
+
283
+ order = sorted(block_value)
284
+ return (
285
+ np.array([block_value[i] for i in order]),
286
+ np.array([block_weight[i] for i in order]),
287
+ np.array([block_span[i] for i in order], dtype=int),
288
+ )