Coverage for evaluation/probability_calibration.py: 100%
135 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Probability calibration for the direction heads (V6.4.0, lead L2). numpy only, pure.
3The multitask / sequence `direction_*` heads emit sigmoid probabilities at ~57-58% accuracy with a weak log-loss. This module
4measures how honest those probabilities are (reliability curve, ECE, Brier, log-loss) and fits the two classic post-hoc maps
5on a validation split only: temperature scaling (one parameter on the logit) and isotonic regression (pool adjacent
6violators). `best_threshold_by_class` picks a per-class decision threshold by balanced accuracy.
7"""
9from __future__ import annotations
11import math
12from typing import TYPE_CHECKING, Any
14import numpy as np
16if TYPE_CHECKING:
17 from collections.abc import Sequence
19 from numpy.typing import ArrayLike
21EPS = 1e-12
24def _clean(probability, outcome) -> tuple[np.ndarray, np.ndarray]:
25 p = np.asarray(probability, dtype=float)
26 y = np.asarray(outcome, dtype=float)
27 keep = np.isfinite(p) & np.isfinite(y)
28 return np.clip(p[keep], EPS, 1.0 - EPS), y[keep]
31def log_loss(probability: ArrayLike, outcome: ArrayLike) -> float | None:
32 """Mean negative log-likelihood of the outcomes under the probabilities; None when empty."""
33 p, y = _clean(probability, outcome)
34 if len(p) == 0:
35 return None
36 return float(-np.mean(y * np.log(p) + (1.0 - y) * np.log(1.0 - p)))
39def brier_score(probability: ArrayLike, outcome: ArrayLike) -> float | None:
40 """Mean squared error of the probabilities against the 0/1 outcomes; None when empty."""
41 p, y = _clean(probability, outcome)
42 return float(np.mean((p - y) ** 2)) if len(p) else None
45def reliability_curve(probability: ArrayLike, outcome: ArrayLike, bins: int = 10) -> list[dict]:
46 """Equal-width bins on [0, 1]: {"low", "high", "n", "mean_probability", "observed_rate"} for each non-empty bin."""
47 p, y = _clean(probability, outcome)
48 edges = np.linspace(0.0, 1.0, bins + 1)
49 index = np.minimum(np.digitize(p, edges[1:-1], right=False), bins - 1)
50 rows = []
51 for position in range(bins):
52 mask = index == position
53 if mask.any():
54 rows.append({"low": float(edges[position]), "high": float(edges[position + 1]), "n": int(mask.sum()),
55 "mean_probability": float(p[mask].mean()), "observed_rate": float(y[mask].mean())})
56 return rows
59def expected_calibration_error(probability: ArrayLike, outcome: ArrayLike, bins: int = 10) -> float | None:
60 """Sample-weighted mean |observed rate - mean probability| over the reliability bins."""
61 rows = reliability_curve(probability, outcome, bins)
62 total = sum(row["n"] for row in rows)
63 if not total:
64 return None
65 return float(sum(row["n"] * abs(row["observed_rate"] - row["mean_probability"]) for row in rows) / total)
68def _logit(p: np.ndarray) -> np.ndarray:
69 return np.log(p / (1.0 - p))
72def _sigmoid(z: np.ndarray) -> np.ndarray:
73 return 1.0 / (1.0 + np.exp(-z))
76def apply_temperature(probability: ArrayLike, temperature: float) -> np.ndarray:
77 """sigmoid(logit(p) / T): T > 1 softens an over-confident head, T < 1 sharpens it, T = 1 is the identity."""
78 p = np.clip(np.asarray(probability, dtype=float), EPS, 1.0 - EPS)
79 return _sigmoid(_logit(p) / float(temperature))
82def fit_temperature(probability: ArrayLike, outcome: ArrayLike, low: float = 0.05, high: float = 20.0, iterations: int = 80) -> float | None:
83 """The temperature minimising log-loss: a golden-section search on log T (the loss is unimodal in it)."""
84 p, y = _clean(probability, outcome)
85 if len(p) < 10 or len(np.unique(y)) < 2:
86 return None
87 ratio = (math.sqrt(5.0) - 1.0) / 2.0
88 a, b = math.log(low), math.log(high)
89 c, d = b - ratio * (b - a), a + ratio * (b - a)
91 def loss(log_t: float) -> float:
92 return float(log_loss(apply_temperature(p, math.exp(log_t)), y))
94 fc, fd = loss(c), loss(d)
95 for _ in range(iterations):
96 if fc < fd:
97 b, d, fd = d, c, fc
98 c = b - ratio * (b - a)
99 fc = loss(c)
100 else:
101 a, c, fc = c, d, fd
102 d = a + ratio * (b - a)
103 fd = loss(d)
104 return float(math.exp((a + b) / 2.0))
107def fit_isotonic(probability: ArrayLike, outcome: ArrayLike) -> dict[str, Any] | None:
108 """Pool-adjacent-violators on outcomes sorted by probability: {"x": block means of p, "y": calibrated rates} (both
109 non-decreasing). None for fewer than 10 usable rows or a single class."""
110 p, y = _clean(probability, outcome)
111 if len(p) < 10 or len(np.unique(y)) < 2:
112 return None
113 order = np.argsort(p, kind="mergesort")
114 p, y = p[order], y[order]
115 blocks = [[float(y[i]), 1.0, float(p[i])] for i in range(len(p))] # [sum of y, count, sum of p]
116 merged: list[list[float]] = []
117 for block in blocks:
118 merged.append(block)
119 while len(merged) > 1 and merged[-2][0] / merged[-2][1] > merged[-1][0] / merged[-1][1]:
120 top = merged.pop()
121 merged[-1] = [merged[-1][0] + top[0], merged[-1][1] + top[1], merged[-1][2] + top[2]]
122 return {"x": [block[2] / block[1] for block in merged], "y": [block[0] / block[1] for block in merged]}
125def apply_isotonic(probability: ArrayLike, fit: dict[str, Any]) -> np.ndarray:
126 """Piecewise-linear interpolation through the fitted block means, flat outside the fitted range."""
127 p = np.clip(np.asarray(probability, dtype=float), 0.0, 1.0)
128 return np.interp(p, fit["x"], fit["y"])
131def best_threshold_by_class(probability: ArrayLike, outcome: ArrayLike, classes: ArrayLike, grid: Sequence[float] | None=None) -> dict[str, dict]:
132 """{class: {"threshold", "balanced_accuracy", "n"}}: the threshold on `grid` (default 0.30..0.70 step 0.05) maximising
133 balanced accuracy among that class's rows. A class lacking both outcomes, or with fewer than 20 rows, gets 0.5."""
134 p = np.asarray(probability, dtype=float)
135 y = np.asarray(outcome, dtype=float)
136 labels = np.asarray([str(value) for value in classes])
137 grid = np.arange(0.30, 0.701, 0.05) if grid is None else np.asarray(grid, dtype=float)
138 out = {}
139 for name in sorted(set(labels)):
140 mask = (labels == name) & np.isfinite(p) & np.isfinite(y)
141 pp, yy = p[mask], y[mask]
142 if len(pp) < 20 or len(np.unique(yy)) < 2:
143 out[name] = {"threshold": 0.5, "balanced_accuracy": None, "n": int(len(pp))}
144 continue
145 best = (-1.0, 0.5)
146 for threshold in grid:
147 call = pp >= threshold
148 tpr = float(call[yy == 1].mean())
149 tnr = float((~call)[yy == 0].mean())
150 score = (tpr + tnr) / 2.0
151 if score > best[0] + 1e-12:
152 best = (score, float(threshold))
153 out[name] = {"threshold": best[1], "balanced_accuracy": best[0], "n": int(len(pp))}
154 return out
157def balanced_accuracy(probability: ArrayLike, outcome: ArrayLike, threshold: float = 0.5) -> float | None:
158 """Mean of the hit rates on up and down outcomes at `threshold`; None without both classes."""
159 p, y = _clean(probability, outcome)
160 if len(p) == 0 or len(np.unique(y)) < 2:
161 return None
162 call = p >= threshold
163 return float((call[y == 1].mean() + (~call)[y == 0].mean()) / 2.0)
166def cross_fitted_log_loss(probability: ArrayLike, outcome: ArrayLike, method: str) -> float | None:
167 """Honest validation log-loss of a calibration method: fit on the first half (time order) and score the second, then
168 swap, and average the two. `method` in {"raw", "temperature", "isotonic"}."""
169 p, y = _clean(probability, outcome)
170 half = len(p) // 2
171 if half < 10:
172 return None
173 losses = []
174 for fit_part, score_part in ((slice(0, half), slice(half, None)), (slice(half, None), slice(0, half))):
175 scored = p[score_part]
176 if method == "raw":
177 calibrated = scored
178 elif method == "temperature":
179 temperature = fit_temperature(p[fit_part], y[fit_part])
180 if temperature is None:
181 return None
182 calibrated = apply_temperature(scored, temperature)
183 elif method == "isotonic":
184 fit = fit_isotonic(p[fit_part], y[fit_part])
185 if fit is None:
186 return None
187 calibrated = np.clip(apply_isotonic(scored, fit), 1e-6, 1.0 - 1e-6)
188 else:
189 raise ValueError(f"unknown calibration method {method!r}")
190 losses.append(log_loss(calibrated, y[score_part]))
191 return float(np.mean(losses))
194def calibration_report(probability: ArrayLike, outcome: ArrayLike, classes: ArrayLike | None=None, bins: int = 10) -> dict[str, Any]:
195 """Everything the L2 decision needs for one head on one split: the raw measures, a reliability curve, both fitted maps
196 with their cross-fitted log-loss, and the per-class thresholds."""
197 p, y = _clean(probability, outcome)
198 report = {
199 "n": int(len(p)), "positive_rate": float(y.mean()) if len(y) else None,
200 "log_loss": log_loss(p, y), "brier": brier_score(p, y), "ece": expected_calibration_error(p, y, bins),
201 "reliability": reliability_curve(p, y, bins),
202 "cross_fitted_log_loss": {method: cross_fitted_log_loss(p, y, method) for method in ("raw", "temperature", "isotonic")},
203 "temperature": fit_temperature(p, y), "isotonic": fit_isotonic(p, y),
204 }
205 if classes is not None:
206 keep = np.isfinite(np.asarray(probability, dtype=float)) & np.isfinite(np.asarray(outcome, dtype=float))
207 report["thresholds_by_class"] = best_threshold_by_class(np.asarray(probability)[keep], np.asarray(outcome)[keep],
208 np.asarray(list(classes))[keep])
209 return report