calibration-proba 0.1.0__py3-none-any.whl

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.
@@ -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
+ )