File size: 19,689 Bytes
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b045445
0164c03
8c15ebd
 
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c15ebd
0164c03
 
 
 
 
 
8c15ebd
 
0164c03
 
 
 
 
 
b045445
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa472f
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b045445
0164c03
b045445
0164c03
 
b045445
8c15ebd
 
0164c03
 
8c15ebd
 
b045445
0164c03
 
 
 
 
b045445
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa472f
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa472f
0164c03
 
 
8fa472f
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa472f
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b045445
0164c03
 
b045445
0164c03
b045445
0164c03
b045445
8c15ebd
0164c03
 
 
 
b045445
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b045445
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa472f
0164c03
 
 
 
 
 
 
 
b045445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
"""Write every LaTeX table of the paper from numbers.json (run after analysis.py). Output: tables/*.tex"""
import json
from pathlib import Path

import sys
HERE = Path(__file__).resolve().parent
# --release DIR: read DIR/results/numbers.json and write DIR/results/tables (public release layout)
RELEASE = Path(sys.argv[sys.argv.index("--release") + 1]).resolve() if "--release" in sys.argv else None
BASE = (RELEASE / "results") if RELEASE else HERE
N = json.loads((BASE / "numbers.json").read_text())
P, D, PAIR, DEC = N["point"], N["deduplicated"], N["paired"], N["decomposition"]
OUT = BASE / "tables"
OUT.mkdir(exist_ok=True)

DISPLAY = {
    "Jev zero-shot": "Jev, bare labels",
    "Jev + form instruction": "Jev, form instruction",
    "Jev + form instruction + definitions": "Jev, instruction + definitions",
    "SemIf bracket": "SemIf (Qwen3.5-4B), bare labels",
    "SemIf bracket + definitions": "SemIf, instruction + definitions",
    "SemIf one-vs-rest": "SemIf, one-vs-rest, bare labels",
    "GLM-5.3 (generative)": "GLM-5.3, bare labels",
    "GLM-5.3, 20 retrieved examples": "GLM-5.3, 20 retrieved labelled examples",
    "20-nearest-neighbour vote": "Vote of the same 20 retrieved examples",
    "1-nearest-neighbour": "Label of the single most similar complaint",
    "GLM-5.3, labels of 20 retrieved complaints": "GLM-5.3, labels of the 20 retrieved (no texts)",
    "TF-IDF + LR": "TF-IDF",
    "LR on Jev probs": "Jev probabilities",
    "TF-IDF + Jev + LR": "TF-IDF + Jev probabilities",
    "LR on sentence embeddings": "Sentence embeddings",
    "TF-IDF + embeddings + LR": "TF-IDF + sentence embeddings",
    "TF-IDF + Jev top choice": "TF-IDF + Jev top choice (one-hot)",
    "TF-IDF + label-name similarity": "TF-IDF + label-name similarity",
    "TF-IDF + stacked embedding probabilities": "TF-IDF + stacked embedding probabilities",
    "TF-IDF, logit-adjusted": "TF-IDF, logit-adjusted",
    "TF-IDF + Jev, logit-adjusted": "TF-IDF + Jev probabilities, logit-adjusted",
    "ModernBERT-base (vanilla)": "ModernBERT-base",
    "ModernBERT-base (distilled)": "ModernBERT-base, distilled",
    "ModernBERT-large": "ModernBERT-large",
    "Qwen3-32B + LoRA": "Qwen3-32B + LoRA",
}
SHORT = {
    "Jev zero-shot": "Jev", "Jev + form instruction": "Jev+instr", "Jev + form instruction + definitions": "Jev+defs",
    "SemIf bracket": "SemIf", "SemIf bracket + definitions": "SemIf+defs", "SemIf one-vs-rest": "SemIf-OvR",
    "GLM-5.3 (generative)": "GLM", "GLM-5.3, 20 retrieved examples": "GLM+20ex", "20-nearest-neighbour vote": "20-NN vote", "1-nearest-neighbour": "1-NN", "GLM-5.3, labels of 20 retrieved complaints": "GLM+20labels", "TF-IDF + LR": "TF-IDF", "LR on Jev probs": "LR(Jev)",
    "TF-IDF + Jev + LR": "TF-IDF+Jev", "LR on sentence embeddings": "LR(Emb)",
    "TF-IDF + embeddings + LR": "TF-IDF+Emb", "ModernBERT-base (vanilla)": "MB-base",
    "TF-IDF + Jev top choice": "TF-IDF+Top", "TF-IDF + label-name similarity": "TF-IDF+Sim",
    "TF-IDF + stacked embedding probabilities": "TF-IDF+StackEmb", "TF-IDF, logit-adjusted": "TF-IDF-LA",
    "TF-IDF + Jev, logit-adjusted": "TF-IDF+Jev-LA",
    "ModernBERT-base (distilled)": "MB-base-KD", "ModernBERT-large": "MB-large", "Qwen3-32B + LoRA": "Qwen",
    "TF-IDF (20k)": "TF-IDF[20k]", "TF-IDF + Jev (20k)": "TF-IDF+Jev[20k]", "TF-IDF + SemIf (20k)": "TF-IDF+SemIf[20k]",
    "Jev probabilities (20k)": "LR(Jev)[20k]", "SemIf probabilities (20k)": "LR(SemIf)[20k]",
}
GROUPS = [
    ("Zero-shot, typed-decision interface (no task-specific training)",
     ["Jev zero-shot", "Jev + form instruction", "Jev + form instruction + definitions",
      "SemIf bracket", "SemIf bracket + definitions", "SemIf one-vs-rest"]),
    ("Zero-shot, general-purpose LLM, generated answer", ["GLM-5.3 (generative)"]),
    ("Labelled examples retrieved at answer time, no training", ["GLM-5.3, 20 retrieved examples", "GLM-5.3, labels of 20 retrieved complaints", "20-nearest-neighbour vote", "1-nearest-neighbour"]),
    ("Logistic regression on the fit set",
     ["TF-IDF + LR", "LR on Jev probs", "TF-IDF + Jev + LR", "LR on sentence embeddings", "TF-IDF + embeddings + LR"]),
    ("Logistic regression on the fit set: other zero-shot or embedding features",
     ["TF-IDF + Jev top choice", "TF-IDF + label-name similarity", "TF-IDF + stacked embedding probabilities"]),
    ("Fine-tuned on the fit set",
     ["ModernBERT-base (vanilla)", "ModernBERT-base (distilled)", "ModernBERT-large", "Qwen3-32B + LoRA"]),
]
DAGGER = {"Qwen3-32B + LoRA"}   # temperature fitted on the evaluation split


def f3(x):
    return f"{x:.3f}"


def signed(x):
    x = 0.0 if abs(x) < 0.0005 else x
    return f"${'+' if x >= 0 else '-'}{abs(x):.3f}$"


def ci(c):
    return f"[{signed(c[0])}, {signed(c[1])}]"


def main_table():
    rows = []
    for title, names in GROUPS:
        names = [n for n in names if n in P]
        if not names:
            continue
        rows.append(r"\midrule" if rows else "")
        rows.append(rf"\multicolumn{{11}}{{@{{}}l}}{{\emph{{{title}}}}} \\")
        for n in names:
            r, d = P[n], D["point"][n]
            ece = "n/a" if r["top_label_ece"] is None else f3(r["top_label_ece"]) + ("$^\\dagger$" if n in DAGGER else "")
            rows.append(f"\\quad {DISPLAY[n]} & {r['status']} & {100 * r['accuracy']:.1f} & {f3(r['macro_f1'])} & "
                        f"{f3(r['head_f1'])} & {f3(r['mid_f1'])} & {f3(r['tail_f1'])} & {r['zero_f1_classes']} & {ece} & "
                        f"{100 * d['accuracy']:.1f} & {f3(d['macro_f1'])} \\\\")
    body = "\n".join(x for x in rows if x)
    (OUT / "main.tex").write_text(r"""\begin{tabular}{@{}l c r r r r r r r r r@{}}
\toprule
 & & \multicolumn{7}{c}{Evaluation split (6,430)} & \multicolumn{2}{c}{Filtered (5,198)} \\
\cmidrule(lr){3-9}\cmidrule(l){10-11}
System & Dev. & Acc & Macro F1 & Head & Mid & Tail & F1${=}0$ & ECE & Acc & Macro F1 \\
""" + body + "\n" + r"""\bottomrule
\end{tabular}
""")


PAIRED_SECTIONS = [
    ("No labelled data: zero-shot systems", [("GLM-5.3 (generative)", "Jev zero-shot"), ("SemIf bracket", "Jev zero-shot"),
                                            ("Jev zero-shot", "Qwen3-32B + LoRA")]),
    ("Labelled examples read to write definitions", [("Jev + form instruction + definitions", "Jev zero-shot"),
                                                   ("SemIf bracket + definitions", "SemIf bracket"),
                                                   ("GLM-5.3 (generative)", "Jev + form instruction + definitions")]),
    ("Labelled examples in the prompt", [("GLM-5.3, 20 retrieved examples", "GLM-5.3 (generative)"),
                                        ("GLM-5.3, labels of 20 retrieved complaints", "GLM-5.3 (generative)"),
                                        ("GLM-5.3, 20 retrieved examples", "GLM-5.3, labels of 20 retrieved complaints"),
                                        ("GLM-5.3, 20 retrieved examples", "20-nearest-neighbour vote"),
                                        ("GLM-5.3, 20 retrieved examples", "TF-IDF + LR"),
                                        ("GLM-5.3, 20 retrieved examples", "TF-IDF + label-name similarity"),
                                        ("GLM-5.3, 20 retrieved examples", "ModernBERT-base (vanilla)")]),
    ("Labelled data, no fine-tuning", [("TF-IDF + LR", "Jev + form instruction + definitions"),
                                      ("TF-IDF + LR", "GLM-5.3 (generative)"),
                                      ("TF-IDF + Jev + LR", "TF-IDF + LR"), ("TF-IDF + Jev top choice", "TF-IDF + LR"),
                                      ("TF-IDF + label-name similarity", "TF-IDF + LR"),
                                      ("TF-IDF + embeddings + LR", "TF-IDF + LR"),
                                      ("TF-IDF + Jev + LR", "TF-IDF + label-name similarity")]),
    ("Labelled data and fine-tuning", [("ModernBERT-base (vanilla)", "TF-IDF + LR"), ("Qwen3-32B + LoRA", "TF-IDF + LR")]),
]


def paired_table():
    rows = []
    for title, pairs in PAIRED_SECTIONS:
        pairs = [(a, b) for a, b in pairs if f"{a} || {b}" in PAIR]
        rows.append(r"\midrule" if rows else "")
        rows.append(rf"\multicolumn{{6}}{{@{{}}l}}{{\emph{{{title}}}}} \\")
        for a, b in pairs:
            k = f"{a} || {b}"
            v, dc = PAIR[k], DEC[k]
            rows.append(f"{SHORT[a]} $-$ {SHORT[b]} & {signed(v['delta'])} {ci(v['ci95'])} & {signed(dc['head']['part'])} & "
                        f"{signed(dc['mid']['part'])} & {signed(dc['tail']['part'])} & "
                        f"${'+' if v['acc_delta'] >= 0 else '-'}{100 * abs(v['acc_delta']):.1f}$ "
                        f"[${'+' if v['acc_ci95'][0] >= 0 else '-'}{100 * abs(v['acc_ci95'][0]):.1f}$, "
                        f"${'+' if v['acc_ci95'][1] >= 0 else '-'}{100 * abs(v['acc_ci95'][1]):.1f}$] \\\\")
    body = "\n".join(x for x in rows if x)
    (OUT / "paired.tex").write_text(r"""\begin{tabular}{@{}l r r r r r@{}}
\toprule
 & & \multicolumn{3}{c}{Parts of $\Delta$ macro F1} & \\
\cmidrule(lr){3-5}
Comparison ($X - Y$) & $\Delta$ macro F1 [interval] & Head & Mid & Tail & $\Delta$ accuracy, points [interval] \\
\midrule
""" + body + "\n" + r"""\bottomrule
\end{tabular}
""")


def appendix_paired():
    """Every paired contrast: three bootstrap conventions for macro and tail F1, plus the filtered subset."""
    rows = []
    for k, v in PAIR.items():
        a, b = k.split(" || ")
        if a not in SHORT or b not in SHORT:
            continue
        f = D["paired"][k]
        rows.append(f"{SHORT[a]} $-$ {SHORT[b]} & {signed(v['delta'])} & {ci(v['ci95'])} & {ci(v['ci95_support_based'])} & "
                    f"{ci(v['ci95_class_stratified'])} & {signed(v['tail_delta'])} & {ci(v['tail_ci95'])} & "
                    f"{ci(v['tail_ci95_class_stratified'])} & {signed(f['delta'])} {ci(f['ci95'])} \\\\")
    (OUT / "appendix_paired.tex").write_text(r"""\begin{tabular}{@{}l r r r r r r r r@{}}
\toprule
 & \multicolumn{4}{c}{Macro F1} & \multicolumn{3}{c}{Tail F1} & Filtered subset \\
\cmidrule(lr){2-5}\cmidrule(lr){6-8}\cmidrule(l){9-9}
Comparison & $\Delta$ & Primary & Supported & Stratified & $\Delta$ & Primary & Stratified & $\Delta$ macro F1 [CI] \\
\midrule
""" + "\n".join(rows) + "\n" + r"""\bottomrule
\end{tabular}
""")


COUNT_LABELS = ["Incorrect information on your report",
                "Problem with a credit reporting company's investigation into an existing problem",
                "Identity theft/Fraud/Embezzlement", "Improper use of your report",
                "Improper contact or sharing of info", "Attempts to collect debt not owed",
                "Customer service/Customer relations"]
COUNT_SYSTEMS = ["Jev zero-shot", "SemIf bracket", "GLM-5.3 (generative)", "Qwen3-32B + LoRA"]


def counts_table():
    pc, tc = N["predicted_counts"], N["true_counts"]
    esc = lambda s: s.replace("&", r"\&")
    short = {COUNT_LABELS[1]: r"Problem with a credit reporting company's investigation\ldots"}
    rows = []
    for lab in COUNT_LABELS:
        rows.append(f"\\lbl{{{esc(short.get(lab, lab))}}} & {tc[lab]:,} & " +
                    " & ".join(f"{pc[s][lab]:,}" for s in COUNT_SYSTEMS if s in pc) + r" \\")
    corr = N["overprediction_correlation"]["Jev zero-shot"]
    corr_row = (r"\midrule" + "\n" + r"Correlation with Jev's over-prediction profile & & 1 & " +
                " & ".join(f"${corr[s]:.2f}$" for s in COUNT_SYSTEMS[1:] if s in corr) + r" \\")
    net = N.get("overprediction_correlation_net_of_frequency", {}).get("Jev zero-shot", {})
    if net:
        corr_row += ("\n" + r"\quad net of log label frequency & & 1 & " +
                     " & ".join(f"${net[s]:.2f}$" for s in COUNT_SYSTEMS[1:] if s in net) + r" \\")
    heads = " & ".join(SHORT[s] if s != "Qwen3-32B + LoRA" else "Qwen" for s in COUNT_SYSTEMS if s in pc)
    (OUT / "counts.tex").write_text(r"""\begin{tabular}{@{}p{0.43\linewidth} r r r r r@{}}
\toprule
Label (evaluation split) & True & """ + heads + r""" \\
\midrule
""" + "\n".join(rows) + "\n" + corr_row + "\n" + r"""\bottomrule
\end{tabular}
""")


def group_table():
    names = [n for _, ns in GROUPS for n in ns if n in P]
    rows = [f"{DISPLAY[n]} & {f3(P[n]['head_f1'])} & {f3(P[n]['mid_f1'])} & {f3(P[n]['tail_f1'])} & "
            f"{f3(P[n]['head_f1_conditional'])} & {f3(P[n]['mid_f1_conditional'])} & {f3(P[n]['tail_f1_conditional'])} \\\\"
            for n in names]
    (OUT / "groups.tex").write_text(r"""\begin{tabular}{@{}l r r r r r r@{}}
\toprule
 & \multicolumn{3}{c}{All examples (primary)} & \multicolumn{3}{c}{Group's own examples only} \\
\cmidrule(lr){2-4}\cmidrule(l){5-7}
System & Head & Mid & Tail & Head & Mid & Tail \\
\midrule
""" + "\n".join(rows) + "\n" + r"""\bottomrule
\end{tabular}
""")


if __name__ == "__main__":
    main_table(); paired_table(); appendix_paired(); counts_table(); group_table()
    print("wrote", sorted(p.name for p in OUT.iterdir()))


def grid_table():
    """Selection-slice macro F1 for every logistic-regression feature set and grid point."""
    art = BASE if RELEASE else HERE.parents[1] / "verification" / "jev_benchmark_artifacts"
    caches = {}
    for f in ("jev-1.13.0_features_selection_cache.json", "embedding_control_selection_cache.json"):
        if (art / f).exists():
            caches.update(json.loads((art / f).read_text()))
    grid = {}
    for k, v in caches.items():
        kind, cfg = k.split(" ", 1)
        cfg = json.loads(cfg)
        grid.setdefault(kind, []).append((cfg, v))
    name = {"tfidf": "TF-IDF", "jev": "Jev probabilities", "tfidf+jev": "TF-IDF + Jev", "emb": "Embeddings",
            "tfidf+emb": "TF-IDF + embeddings"}
    blocks = []
    for kinds, Cs in [(["jev", "emb"], [0.01, 0.1, 1.0, 10.0]), (["tfidf", "tfidf+jev", "tfidf+emb"], [1.0, 10.0, 30.0, 100.0])]:
        rows = []
        for kind in kinds:
            if kind not in grid:
                continue
            best = max(v for _, v in grid[kind])
            ws = sorted({c.get("w") for c, _ in grid[kind]}, key=lambda x: (x is None, x))
            for w in ws:
                for cw in (None, "balanced"):
                    cells = []
                    for C in Cs:
                        m = [v for c, v in grid[kind] if c["C"] == C and c["class_weight"] == cw and c.get("w") == w]
                        cells.append("n/a" if not m else (rf"\textbf{{{m[0]:.3f}}}" if m[0] == best else f"{m[0]:.3f}"))
                    wl = "" if w is None else f" ($w{{=}}{w:g}$)"
                    rows.append(f"{name[kind]}{wl} & {'balanced' if cw else 'none'} & " + " & ".join(cells) + r" \\")
        head = " & ".join(f"$C{{=}}{C:g}$" for C in Cs)
        blocks.append(r"\begin{tabular}{@{}l l r r r r@{}}" + "\n\\toprule\nFeatures & Class weight & " + head +
                      " \\\\\n\\midrule\n" + "\n".join(rows) + "\n\\bottomrule\n\\end{tabular}")
    (OUT / "grid.tex").write_text("\n\n\\smallskip\n".join(blocks[::-1]) + "\n")


if __name__ == "__main__":
    grid_table()


def ladder_table():
    """Resource ladder: best system per rung, from numbers.json (point metrics + learning curve)."""
    lc = {(r["model"], r["n"]): {"accuracy": r["accuracy_mean"], "macro_f1": r["macro_f1_mean"]}
          for r in N.get("learning_curve_nested", [])}
    pt = lambda n: (P[n]["accuracy"], P[n]["macro_f1"])
    rows = []
    def add(res, name, a, f, ja=None, jf=None):
        extra = f"{100 * ja:.1f} & {jf:.3f}" if ja is not None else " & "
        rows.append(f"{res} & {name} & {100 * a:.1f} & {f:.3f} & {extra} \\\\")
    add("None", "GLM-5.3 (best zero-shot, bare labels)", *pt("GLM-5.3 (generative)"))
    add("Examples read to write definitions", "Jev + definitions", *pt("Jev + form instruction + definitions"))
    if "GLM-5.3, 20 retrieved examples" in P:
        add("Labelled pool searched at answer time", "GLM-5.3, 20 retrieved examples", *pt("GLM-5.3, 20 retrieved examples"))
    for n in (500, 2000, 8000, 20000):
        if ("tfidf", n) in lc:
            add(f"{n:,} labelled complaints", "TF-IDF", lc[("tfidf", n)]["accuracy"], lc[("tfidf", n)]["macro_f1"],
                lc[("tfidf+jev", n)]["accuracy"], lc[("tfidf+jev", n)]["macro_f1"])
    add("79,278 labelled complaints", "TF-IDF", *pt("TF-IDF + LR"), *pt("TF-IDF + Jev + LR"))
    add("", "TF-IDF + label-name similarity", *pt("TF-IDF + label-name similarity"))
    add("79,278 labelled complaints + GPU", "ModernBERT-base, fine-tuned", *pt("ModernBERT-base (vanilla)"))
    add("", "Qwen3-32B + LoRA, fine-tuned (status C)", *pt("Qwen3-32B + LoRA"))
    (OUT / "ladder.tex").write_text(r"""\begin{tabular}{@{}l l r r r r@{}}
\toprule
 & & & & \multicolumn{2}{c}{+ Jev probabilities} \\
\cmidrule(l){5-6}
Labelled data & System & Acc & Macro F1 & Acc & Macro F1 \\
\midrule
""" + "\n".join(rows) + "\n" + r"""\bottomrule
\end{tabular}
""")


if __name__ == "__main__":
    ladder_table()


def ranked_table():
    """Every system, sorted by macro F1: the simple lookup table (Appendix A)."""
    kind = {}
    for title, names in GROUPS:
        for n in names:
            kind[n] = ("Zero-shot" if title.startswith("Zero-shot") else
                       "Retrieval, no training" if title.startswith("Labelled examples") else
                       "Fine-tuned" if title.startswith("Fine-tuned") else "Logistic regression")
    names = sorted([n for n in kind if n in P], key=lambda n: -P[n]["macro_f1"])
    rows = [f"{i} & {DISPLAY[n]} & {kind[n]} & {P[n]['macro_f1']:.3f} & {100 * P[n]['accuracy']:.1f} \\\\"
            for i, n in enumerate(names, 1)]
    (OUT / "ranked.tex").write_text(r"""\begin{tabular}{@{}r l l r r@{}}
\toprule
 & System & Training & Macro F1 & Acc \\
\midrule
""" + "\n".join(rows) + "\n" + r"""\bottomrule
\end{tabular}
""")


if __name__ == "__main__":
    ranked_table()


def scoring_table():
    """Log-loss (probability floored at 1e-6) and Brier score for every system that returns a distribution."""
    sc = N.get("scoring", {})
    names = [n for _, ns in GROUPS for n in ns if n in sc]
    rows = [f"{DISPLAY[n]} & {sc[n]['nll_floor_1e-6']:.2f} & {sc[n]['brier']:.3f} & {100 * sc[n]['p_true_is_zero']:.1f} \\\\"
            for n in names]
    (OUT / "scoring.tex").write_text(r"""\begin{tabular}{@{}l r r r@{}}
\toprule
System & Log-loss & Brier & True label at 0 (percent) \\
\midrule
""" + "\n".join(rows) + "\n" + r"""\bottomrule
\end{tabular}
""")


if __name__ == "__main__":
    scoring_table()


def merge_table():
    """Year test for historical label pairs (Appendix H), from numbers.json year_test."""
    yt = N.get("year_test", [])
    rows, notes, marks = [], [], "abcdefgh"
    for r in sorted(yt, key=lambda r: not r["kept"]):
        merged = "yes" if r["kept"] else "no"
        few = [(w, r[f"{w}_with_year"]) for w in ("old", "new") if r[f"{w}_with_year"] < 20]
        if few and not r["kept"]:
            m = marks[len(notes)]
            merged += f"$^{m}$"
            w, k = few[0]
            notes.append(f"$^{m}$Only {k} {'newer' if w == 'new' else 'older'}-label complaints mention a year.")
        rows.append(rf"\lbl{{{r['old']}}} & \lbl{{{r['new']}}} & {r['old_share_le_2016']:.2f} & "
                    rf"{r['new_share_ge_2017']:.2f} & {merged} \\")
    (OUT / "merge.tex").write_text(
        r"""\begin{tabular}{@{}>{\raggedright\arraybackslash}p{0.29\linewidth}>{\raggedright\arraybackslash}p{0.34\linewidth}r r l@{}}
\toprule
Older label & Newer label & Older $\le$2016 & Newer $\ge$2017 & Merged \\
\midrule
""" + "\n".join(rows) + "\n" + r"""\bottomrule
\end{tabular}

\smallskip
""" + " ".join(notes) + "\n")


if __name__ == "__main__":
    merge_table()