File size: 8,025 Bytes
d231962
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
"""Macro F0.5 exactly as `ps.pdf` defines it.

Per S1 entity:
    F0.5 = (1.25 * P * R) / (0.25 * P + R)
macro-averaged over ALL S1 entities. A singleton (no true match) scores 1.0 for a correct
empty prediction and 0.0 for any prediction.

Substituting P = TP/k and R = TP/T collapses this to the identity the whole project relies on:

    F0.5 = 1.25 * TP / (0.25 * T + k)

because FP = k - TP and FN = T - TP cancel the TP contributions in the denominator. This is
exact, not an approximation.

THE BREAK-EVEN EXCHANGE RATE, derived from that identity. With D = 0.25T + k, adding one
prediction
  * gains  1.25 (D - TP) / (D (D+1))   if it is a true positive
  * loses  1.25 TP      / (D (D+1))    if it is a false positive
so an extra pair is worth taking only when its TP:FP ratio beats

    TP / (D - TP)

This is an OPERATING-POINT-DEPENDENT number, not a universal constant. In the idealised limit
TP -> T and k -> T (so D = 1.25T) it tends to T / 0.25T = 4. At the shipped operating point it
is lower: measured mean T = 3.449, mean k = 3.316, mean TP = 3.300 over 20,000 validation
entities gives D = 4.178 and a break-even of 3.300 / 0.878 = ~3.8:1.

    Any batch of pairs added to the prediction set must be better than roughly 3.8-4 true
    for every 1 false - about 80% precision - or macro F0.5 falls.

(An earlier version of this analysis asserted "exactly 4:1". That is only the limiting value;
the self-test below checks the formula itself rather than the round number.)

Measured on validation, the best band below our threshold offered 1.90:1 (386 TP / 203 FP),
and the next best 1.54:1. Both are far under the break-even either way, which is why lowering
the threshold could not buy recall, and why any new candidate source has to clear ~80%
precision to be worth including at all.
"""
from __future__ import annotations

import numpy as np


def entity_f05(pred: set, truth: set) -> float:
    """F0.5 for one S1 entity. `pred` and `truth` are sets of S2/S3 identifiers."""
    k, t = len(pred), len(truth)
    if t == 0:
        return 1.0 if k == 0 else 0.0           # singleton: empty is perfect, anything is 0
    if k == 0:
        return 0.0
    tp = len(pred & truth)
    if tp == 0:
        return 0.0
    return 1.25 * tp / (0.25 * t + k)


def macro_f05(preds: dict, truths: dict, ids):
    """Macro F0.5 over `ids`.

    preds  : {entity -> iterable of predicted targets}  (missing == predicted empty)
    truths : {entity -> iterable of true targets}       (missing == true singleton)
    ids    : the entity list to average over - MUST be every S1 entity being scored, not
             just the ones with predictions, or singletons silently vanish from the average.

    Returns (summary_dict, per_entity_array).
    """
    per = np.empty(len(ids), np.float64)
    tp_sum = k_sum = t_sum = 0
    for i, q in enumerate(ids):
        p = preds.get(q) or ()
        t = truths.get(q) or ()
        p = p if isinstance(p, set) else set(p)
        t = t if isinstance(t, set) else set(t)
        per[i] = entity_f05(p, t)
        tp_sum += len(p & t)
        k_sum += len(p)
        t_sum += len(t)
    return {
        "f05": float(per.mean()) if len(per) else 0.0,
        "precision": (tp_sum / k_sum) if k_sum else 0.0,   # pooled, for diagnosis only
        "recall": (tp_sum / t_sum) if t_sum else 0.0,
        "n": len(ids),
        "tp": tp_sum, "k": k_sum, "t": t_sum,
        "pred_per_entity": (k_sum / len(ids)) if len(ids) else 0.0,
    }, per


def entity_scores(preds: dict, truths: dict, ids):
    return macro_f05(preds, truths, ids)[1]


def slice_report(preds: dict, truths: dict, ids, by: dict, label="slice"):
    """Macro F0.5 broken out by an arbitrary per-entity key (country, singleton flag, ...).

    Model-1's contribution to the project was that slice-level reporting is where the real
    failures show up: the shipped run scored us 0.9832 / india 0.9806 on validation while
    France - which has no labels at all - came out at an implied 0.946.
    """
    groups: dict = {}
    for q in ids:
        groups.setdefault(by.get(q, "?"), []).append(q)
    rows = []
    for key in sorted(groups, key=str):
        g = groups[key]
        m, _ = macro_f05(preds, truths, g)
        rows.append({label: key, "n": len(g), "f05": m["f05"],
                     "precision": m["precision"], "recall": m["recall"],
                     "pred_per_entity": m["pred_per_entity"]})
    return rows


def oracle_f05(candidates: dict, truths: dict, ids):
    """Best macro F0.5 reachable from a candidate set: predict truth AND candidates, and
    predict empty for genuine singletons.

    THE CEILING THAT MATTERS. Measured on the shipped candidates this was 0.9942 against a
    shipped 0.9821 - so the scorer lost 0.0121 and blocking lost 0.0058. Model-5 s25 is right
    that you must never optimise the decision layer while this number is the bottleneck.

    Note the distinction Model-5 s33 rule 9 insists on: this is NOT pair recall. Pair recall
    on the same candidates was 0.9824, which is a different and much less useful number.
    """
    preds = {}
    for q in ids:
        hit = set(candidates.get(q) or ()) & set(truths.get(q) or ())
        if hit:
            preds[q] = hit
    return macro_f05(preds, truths, ids)


def pair_recall(candidates: dict, truths: dict, ids):
    """Fraction of true pairs present in the candidate set, plus per-entity coverage rates."""
    got = tot = 0
    all_present = 0
    n_nonsing = 0
    for q in ids:
        t = set(truths.get(q) or ())
        if not t:
            continue
        n_nonsing += 1
        c = set(candidates.get(q) or ())
        h = len(t & c)
        got += h
        tot += len(t)
        if h == len(t):
            all_present += 1
    return {
        "pair_recall": got / tot if tot else 0.0,
        "true_pairs": tot,
        "retrieved": got,
        "all_match_rate": all_present / n_nonsing if n_nonsing else 0.0,
    }


# --------------------------------------------------------------------------- self-test
def _selftest():
    """ps.pdf's worked example: one true positive, three true matches, one prediction."""
    got = entity_f05({"a"}, {"a", "b", "c"})
    assert abs(got - 0.7142857) < 1e-6, got                      # 1.25*1/(0.75+1)
    assert entity_f05(set(), set()) == 1.0                       # singleton, empty
    assert entity_f05({"a"}, set()) == 0.0                       # singleton, predicted
    assert entity_f05(set(), {"a"}) == 0.0                       # missed everything
    assert entity_f05({"a"}, {"a"}) == 1.0                       # perfect
    assert abs(entity_f05({"a", "x"}, {"a"}) - 1.25 / 2.25) < 1e-9

    # Break-even exchange rate: verify TP/(D-TP) against brute-force deltas, and confirm it
    # tends to 4 only in the limit TP -> T, k -> T.
    def brute_ratio(T, TP, k):
        D = 0.25 * T + k
        base = 1.25 * TP / D
        gain = 1.25 * (TP + 1) / (0.25 * T + k + 1) - base       # one more, correct
        loss = base - 1.25 * TP / (0.25 * T + k + 1)             # one more, wrong
        return gain, loss, loss / gain, TP / (D - TP)

    for T, TP, k in [(4, 3, 3), (10, 9, 9), (100, 99, 99), (4, 2, 2), (8, 7, 8)]:
        gain, loss, emp, formula = brute_ratio(T, TP, k)
        assert gain > 0 and loss > 0
        assert abs(emp - formula) < 1e-9, (T, TP, k, emp, formula)

    # the limit: as TP=k=T grows, TP/(D-TP) -> 4
    lim = [brute_ratio(T, T - 1, T - 1)[3] for T in (4, 40, 400, 4000)]
    assert lim[-1] > 3.9 and lim[0] < lim[-1] < 4.0, lim

    # the shipped operating point (20,000 val entities): T=68,983 k=66,324 TP=66,009
    n = 20000
    T, k, TP = 68983 / n, 66324 / n, 66009 / n
    D = 0.25 * T + k
    shipped = TP / (D - TP)
    assert 3.6 < shipped < 3.9, shipped
    print(f"evaluate.py self-test OK (ps.pdf example = 0.714286; "
          f"break-even formula verified; shipped operating point = {shipped:.2f}:1, "
          f"limit -> 4:1)")


if __name__ == "__main__":
    _selftest()