onelook 0.1.2__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.
onelook/metrics.py ADDED
@@ -0,0 +1,407 @@
1
+ """Scoring helpers for binary decisions: matched or not, positive or not.
2
+
3
+ All of this is plain arithmetic over labelled items. Quantities that are
4
+ undefined are returned as ``None`` rather than as 0 or 1:
5
+
6
+ * precision is ``None`` when nothing was predicted positive,
7
+ * recall is ``None`` when there are no gold positives,
8
+ * F1 is ``None`` when there are no gold positives and no predicted
9
+ positives (otherwise ``2*tp / (2*tp + fp + fn)``),
10
+ * accuracy is ``None`` when there are no items.
11
+
12
+ With a threshold, an item is predicted positive when ``score >= threshold``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import csv
18
+ import hashlib
19
+ import json
20
+ import math
21
+ import os
22
+ from dataclasses import dataclass
23
+ from statistics import NormalDist
24
+ from typing import Iterable, Sequence
25
+
26
+ TUNED_WARNING = (
27
+ "threshold was chosen on the same data it is reported on; "
28
+ "the result is the best any threshold reaches on this data, not an estimate for unseen data"
29
+ )
30
+
31
+ _TRUE = {"1", "true", "yes"}
32
+ _FALSE = {"0", "false", "no"}
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Item:
37
+ """One labelled example. ``score`` or ``pred`` (or both) should be set."""
38
+
39
+ gold: bool
40
+ score: float | None = None
41
+ pred: bool | None = None
42
+ id: str | None = None
43
+ text: str | None = None
44
+
45
+
46
+ def _ratio(numerator: int, denominator: int) -> float | None:
47
+ return numerator / denominator if denominator else None
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class Confusion:
52
+ """Confusion counts and the measures that follow from them."""
53
+
54
+ tp: int = 0
55
+ fp: int = 0
56
+ fn: int = 0
57
+ tn: int = 0
58
+
59
+ @property
60
+ def n(self) -> int:
61
+ return self.tp + self.fp + self.fn + self.tn
62
+
63
+ @property
64
+ def precision(self) -> float | None:
65
+ return _ratio(self.tp, self.tp + self.fp)
66
+
67
+ @property
68
+ def recall(self) -> float | None:
69
+ return _ratio(self.tp, self.tp + self.fn)
70
+
71
+ @property
72
+ def f1(self) -> float | None:
73
+ return _ratio(2 * self.tp, 2 * self.tp + self.fp + self.fn)
74
+
75
+ @property
76
+ def accuracy(self) -> float | None:
77
+ return _ratio(self.tp + self.tn, self.n)
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class Result:
82
+ """Scores for one set of items at one threshold (or from ``pred``).
83
+
84
+ ``threshold_tuned_on_same_data`` is True when the threshold came from
85
+ :func:`best_f1_threshold` run on these same items, False when it came
86
+ from a search on different items, and None when the threshold was given
87
+ as a plain number (onelook cannot know where a number came from).
88
+ """
89
+
90
+ confusion: Confusion
91
+ threshold: float | None = None
92
+ threshold_tuned_on_same_data: bool | None = None
93
+
94
+ @property
95
+ def n(self) -> int:
96
+ return self.confusion.n
97
+
98
+ @property
99
+ def precision(self) -> float | None:
100
+ return self.confusion.precision
101
+
102
+ @property
103
+ def recall(self) -> float | None:
104
+ return self.confusion.recall
105
+
106
+ @property
107
+ def f1(self) -> float | None:
108
+ return self.confusion.f1
109
+
110
+ @property
111
+ def accuracy(self) -> float | None:
112
+ return self.confusion.accuracy
113
+
114
+ @property
115
+ def warning(self) -> str | None:
116
+ return TUNED_WARNING if self.threshold_tuned_on_same_data else None
117
+
118
+ def interval(self, measure: str, confidence: float = 0.95) -> tuple[float, float] | None:
119
+ """Wilson interval for ``"precision"``, ``"recall"`` or ``"accuracy"``.
120
+
121
+ F1 is not a simple proportion, so no interval is offered for it.
122
+ """
123
+ c = self.confusion
124
+ counts = {
125
+ "precision": (c.tp, c.tp + c.fp),
126
+ "recall": (c.tp, c.tp + c.fn),
127
+ "accuracy": (c.tp + c.tn, c.n),
128
+ }
129
+ if measure not in counts:
130
+ raise ValueError(f"no interval for {measure!r}; use precision, recall or accuracy")
131
+ return wilson_interval(*counts[measure], confidence=confidence)
132
+
133
+ def to_dict(self) -> dict:
134
+ """A JSON-ready dict, suitable as a metrics file for ``onelook run``."""
135
+ c = self.confusion
136
+ out = {
137
+ "n": c.n,
138
+ "tp": c.tp,
139
+ "fp": c.fp,
140
+ "fn": c.fn,
141
+ "tn": c.tn,
142
+ "precision": c.precision,
143
+ "recall": c.recall,
144
+ "f1": c.f1,
145
+ "accuracy": c.accuracy,
146
+ "threshold": self.threshold,
147
+ "threshold_tuned_on_same_data": self.threshold_tuned_on_same_data,
148
+ }
149
+ if self.warning:
150
+ out["warning"] = self.warning
151
+ return out
152
+
153
+
154
+ @dataclass(frozen=True)
155
+ class ThresholdChoice:
156
+ """A threshold found by :func:`best_f1_threshold`.
157
+
158
+ ``threshold`` is None when F1 is undefined or zero at every threshold
159
+ (no items, or no gold positives); scoring with such a choice predicts
160
+ nothing positive. ``result`` holds the scores on the data searched,
161
+ flagged as tuned on that data.
162
+ """
163
+
164
+ threshold: float | None
165
+ result: Result
166
+ candidates: int
167
+ data_digest: str
168
+
169
+
170
+ @dataclass(frozen=True)
171
+ class Errors:
172
+ """Every miss: items wrongly predicted positive, and wrongly negative."""
173
+
174
+ false_positives: tuple[Item, ...]
175
+ false_negatives: tuple[Item, ...]
176
+
177
+ @property
178
+ def all(self) -> tuple[Item, ...]:
179
+ return self.false_positives + self.false_negatives
180
+
181
+
182
+ # --------------------------------------------------------------------------
183
+ # Reading
184
+
185
+
186
+ def _to_bool(value, where: str, column: str) -> bool:
187
+ if isinstance(value, bool):
188
+ return value
189
+ if isinstance(value, (int, float)) and value in (0, 1):
190
+ return bool(value)
191
+ if isinstance(value, str) and value.strip().lower() in _TRUE:
192
+ return True
193
+ if isinstance(value, str) and value.strip().lower() in _FALSE:
194
+ return False
195
+ raise ValueError(f"{where}: {column} must be 1/0, true/false or yes/no, got {value!r}")
196
+
197
+
198
+ def _to_score(value, where: str) -> float:
199
+ try:
200
+ if isinstance(value, bool):
201
+ raise ValueError
202
+ score = float(value)
203
+ except (TypeError, ValueError):
204
+ raise ValueError(f"{where}: score must be a number, got {value!r}") from None
205
+ if math.isnan(score):
206
+ raise ValueError(f"{where}: score is NaN")
207
+ return score
208
+
209
+
210
+ def _blank(value) -> bool:
211
+ return value is None or (isinstance(value, str) and not value.strip())
212
+
213
+
214
+ def _item(row: dict, where: str) -> Item:
215
+ if _blank(row.get("gold")):
216
+ raise ValueError(f"{where}: missing 'gold'")
217
+ score = None if _blank(row.get("score")) else _to_score(row["score"], where)
218
+ pred = None if _blank(row.get("pred")) else _to_bool(row["pred"], where, "pred")
219
+ if score is None and pred is None:
220
+ raise ValueError(f"{where}: needs 'score' or 'pred'")
221
+ return Item(
222
+ gold=_to_bool(row["gold"], where, "gold"),
223
+ score=score,
224
+ pred=pred,
225
+ id=None if _blank(row.get("id")) else str(row["id"]),
226
+ text=None if _blank(row.get("text")) else str(row["text"]),
227
+ )
228
+
229
+
230
+ def load_items(path: str | os.PathLike) -> list[Item]:
231
+ """Read items from ``.csv`` (with a header row) or ``.jsonl`` / ``.ndjson``.
232
+
233
+ Columns / keys: ``gold`` (required), ``score`` and/or ``pred``, and
234
+ optionally ``id`` and ``text``. Others are ignored.
235
+ """
236
+ path = os.fspath(path)
237
+ extension = os.path.splitext(path)[1].lower()
238
+ items = []
239
+ if extension == ".csv":
240
+ with open(path, encoding="utf-8-sig", newline="") as handle:
241
+ reader = csv.DictReader(handle)
242
+ for row in reader:
243
+ if not any(not _blank(v) for v in row.values()):
244
+ continue
245
+ items.append(_item(row, f"{path}, line {reader.line_num}"))
246
+ elif extension in (".jsonl", ".ndjson"):
247
+ with open(path, encoding="utf-8-sig") as handle:
248
+ for number, line in enumerate(handle, start=1):
249
+ if not line.strip():
250
+ continue
251
+ where = f"{path}, line {number}"
252
+ try:
253
+ row = json.loads(line)
254
+ except ValueError as exc:
255
+ raise ValueError(f"{where}: not valid JSON ({exc})") from None
256
+ if not isinstance(row, dict):
257
+ raise ValueError(f"{where}: expected a JSON object")
258
+ items.append(_item(row, where))
259
+ else:
260
+ raise ValueError(f"{path}: unsupported format; use .csv, .jsonl or .ndjson")
261
+ return items
262
+
263
+
264
+ # --------------------------------------------------------------------------
265
+ # Scoring
266
+
267
+
268
+ def _predictions(items: Sequence[Item], threshold: float | None, use_pred: bool) -> list[bool]:
269
+ out = []
270
+ for index, item in enumerate(items):
271
+ if use_pred:
272
+ if item.pred is None:
273
+ raise ValueError(f"item {index} ({item.id!r}) has no 'pred'")
274
+ out.append(item.pred)
275
+ else:
276
+ if item.score is None:
277
+ raise ValueError(f"item {index} ({item.id!r}) has no 'score'")
278
+ out.append(threshold is not None and item.score >= threshold)
279
+ return out
280
+
281
+
282
+ def _count(items: Sequence[Item], predictions: Sequence[bool]) -> Confusion:
283
+ tp = fp = fn = tn = 0
284
+ for item, predicted in zip(items, predictions):
285
+ if predicted and item.gold:
286
+ tp += 1
287
+ elif predicted:
288
+ fp += 1
289
+ elif item.gold:
290
+ fn += 1
291
+ else:
292
+ tn += 1
293
+ return Confusion(tp=tp, fp=fp, fn=fn, tn=tn)
294
+
295
+
296
+ def confusion(items: Iterable[Item], threshold: float | None = None) -> Confusion:
297
+ """Confusion counts at a threshold, or from ``pred`` when it is None."""
298
+ items = list(items)
299
+ return _count(items, _predictions(items, threshold, use_pred=threshold is None))
300
+
301
+
302
+ def _digest(items: Sequence[Item]) -> str:
303
+ lines = sorted(f"{int(i.gold)}\t{i.score!r}\n" for i in items)
304
+ return hashlib.sha256("".join(lines).encode("ascii")).hexdigest()
305
+
306
+
307
+ def score_at(items: Iterable[Item], threshold: "float | ThresholdChoice") -> Result:
308
+ """Score items at a threshold (positive when ``score >= threshold``).
309
+
310
+ Pass the :class:`ThresholdChoice` from :func:`best_f1_threshold` rather
311
+ than its number, and the result records whether the threshold was chosen
312
+ on these same items.
313
+ """
314
+ items = list(items)
315
+ if isinstance(threshold, ThresholdChoice):
316
+ value = threshold.threshold
317
+ tuned = _digest(items) == threshold.data_digest
318
+ return Result(_count(items, _predictions(items, value, use_pred=False)), value, tuned)
319
+ value = float(threshold)
320
+ if math.isnan(value):
321
+ raise ValueError("threshold is NaN")
322
+ return Result(_count(items, _predictions(items, value, use_pred=False)), value, None)
323
+
324
+
325
+ def score_predictions(items: Iterable[Item]) -> Result:
326
+ """Score items by their ``pred`` field."""
327
+ items = list(items)
328
+ return Result(_count(items, _predictions(items, None, use_pred=True)))
329
+
330
+
331
+ def best_f1_threshold(items: Iterable[Item]) -> ThresholdChoice:
332
+ """Find the threshold with the highest F1 on these items.
333
+
334
+ Candidates are the distinct scores present. Items with equal scores
335
+ always fall on the same side. When several thresholds give the same F1,
336
+ the highest threshold is returned.
337
+
338
+ This is for giving a baseline its best case. The numbers in ``result``
339
+ are then tuned on the data they describe and are flagged as such.
340
+ """
341
+ items = list(items)
342
+ _predictions(items, 0.0, use_pred=False) # every item must have a score
343
+ digest = _digest(items)
344
+ positives = sum(1 for i in items if i.gold)
345
+ ordered = sorted(items, key=lambda i: i.score, reverse=True)
346
+ best: tuple[int, int, float] | None = None # (2*tp, tp+fp+positives, threshold)
347
+ tp = fp = 0
348
+ candidates = 0
349
+ index = 0
350
+ while index < len(ordered):
351
+ score = ordered[index].score
352
+ while index < len(ordered) and ordered[index].score == score:
353
+ if ordered[index].gold:
354
+ tp += 1
355
+ else:
356
+ fp += 1
357
+ index += 1
358
+ candidates += 1
359
+ numerator, denominator = 2 * tp, tp + fp + positives
360
+ # Exact comparison of fractions; strict, so the highest threshold
361
+ # wins a tie.
362
+ if numerator > 0 and (best is None or numerator * best[1] > best[0] * denominator):
363
+ best = (numerator, denominator, score)
364
+ threshold = best[2] if best else None
365
+ result = Result(
366
+ _count(items, _predictions(items, threshold, use_pred=False)), threshold, True
367
+ )
368
+ return ThresholdChoice(threshold, result, candidates, digest)
369
+
370
+
371
+ def errors(items: Iterable[Item], threshold: "float | ThresholdChoice | None" = None) -> Errors:
372
+ """List every false positive and false negative, in input order.
373
+
374
+ With ``threshold`` None the ``pred`` field decides.
375
+ """
376
+ items = list(items)
377
+ if isinstance(threshold, ThresholdChoice):
378
+ predictions = _predictions(items, threshold.threshold, use_pred=False)
379
+ else:
380
+ predictions = _predictions(items, threshold, use_pred=threshold is None)
381
+ return Errors(
382
+ false_positives=tuple(i for i, p in zip(items, predictions) if p and not i.gold),
383
+ false_negatives=tuple(i for i, p in zip(items, predictions) if not p and i.gold),
384
+ )
385
+
386
+
387
+ def wilson_interval(
388
+ successes: int, n: int, confidence: float = 0.95
389
+ ) -> tuple[float, float] | None:
390
+ """Wilson score interval for a proportion, without continuity correction.
391
+
392
+ Returns ``(low, high)``, or None when ``n`` is 0.
393
+ """
394
+ if n < 0 or successes < 0 or successes > n:
395
+ raise ValueError(f"need 0 <= successes <= n, got {successes} of {n}")
396
+ if not 0 < confidence < 1:
397
+ raise ValueError("confidence must be between 0 and 1")
398
+ if n == 0:
399
+ return None
400
+ z = NormalDist().inv_cdf(0.5 + confidence / 2)
401
+ p = successes / n
402
+ denominator = 1 + z * z / n
403
+ centre = (p + z * z / (2 * n)) / denominator
404
+ half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denominator
405
+ low = 0.0 if successes == 0 else max(0.0, centre - half)
406
+ high = 1.0 if successes == n else min(1.0, centre + half)
407
+ return low, high