PopTurk / code /scripts /20_fp_diag.py
Jyo-K's picture
Upload folder using huggingface_hub
d231962 verified
Raw
History Blame Contribute Delete
8.62 kB
"""Diagnose the false positives. 0.0041 of val loss, 24% of the total, undiagnosed by anyone.
Every document in this project has attacked false NEGATIVES. FALSE_NEGATIVES_2026-09-27.md
s1 lists FP at 0.0041 and MODEL5_FALSE_NEGATIVE_FIXES.md s6 records it as "not diagnosed
yet [?]". It is now the largest unexamined bucket in the US/India half, and the arithmetic
says US/India must gain +0.0045 val for the leaderboard to reach 0.990 - so this bucket
alone is roughly the size of what is needed.
THE QUESTION THAT DECIDES WHAT TO BUILD. A predicted pair (q, c) that is wrong is wrong in
one of three ways, and they need completely different fixes:
A. c belongs to a DIFFERENT S1, and that S1 is also in our candidate table.
-> an arbitration / ranking failure. We had the right answer and chose the wrong one.
-> fixable with better global assignment. No new retrieval, no new scoring.
B. c belongs to a different S1 that is NOT in our candidate table for c.
-> a retrieval failure wearing a false-positive costume: the true owner never competed.
-> fixable only by retrieving more.
C. c belongs to NO S1 (a true distractor).
-> a scoring failure. 26.8% of addressed pool records are distractors, and 22.5% of
those deliberately reuse a real S1 name.
-> fixable only with a better scorer or better features.
The split between A, B and C is the whole answer, and one pass over the labelled val split
settles it. Run:
python scripts/20_fp_diag.py --bundle work/rescore/bundle.joblib
With no bundle it fits a quick stacker on g_stack first, so it can run standalone.
"""
from __future__ import annotations
import argparse
import collections
import os
import sys
import numpy as np
import pandas as pd
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from berx import evaluate as E # noqa: E402
from berx import fuse as F # noqa: E402
from berx import paths as P # noqa: E402
from berx import structure as S # noqa: E402
BASE = ["p1", "p1_rank", "p1_gap", "ce"]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--bundle", default="")
ap.add_argument("--split", default="train")
ap.add_argument("--max-examples", type=int, default=12)
a = ap.parse_args()
df = pd.read_parquet(P.work("m4", "train.parquet"))
d = os.path.dirname(P.work("prep", a.split, "_"))
s1 = pd.read_parquet(os.path.join(d, "source1.parquet"))
pool = pd.read_parquet(os.path.join(d, "pool.parquet"))
# the six measured features, so the decision resembles what actually ships
s1 = pd.concat([s1, S.name_key_columns(s1)], axis=1)
pool = pd.concat([pool, S.name_key_columns(pool)], axis=1)
pool["addr_empty"] = pool["business_address"].astype(str).str.strip() == ""
nf = S.name_features(df, s1, pool)
for c in S.NAME_FEATURES:
df[c] = nf[c].to_numpy()
feats = BASE + S.NAME_FEATURES
tr, va = df[df.grp == "stack"], df[df.grp == "val"].copy()
if a.bundle and os.path.exists(a.bundle):
import joblib
b = joblib.load(a.bundle)
feats = [f for f in b["feats"] if f in va.columns]
if len(feats) != len(b["feats"]):
print(" bundle wants features this table lacks; refitting instead")
b = F.fit_stacker(tr, BASE + S.NAME_FEATURES, label="y", group="q", n_folds=3)
else:
b = F.fit_stacker(tr, feats, label="y", group="q", n_folds=3)
va["p"] = F.apply_stacker(b, va)
t = np.load(P.work("m4", "truth.npz"))
ids = sorted(va["q"].unique().tolist())
idset = set(ids)
truths = {q: set() for q in ids}
keep = np.isin(t["gt_q"], ids)
for q, c in zip(t["gt_q"][keep], t["gt_c"][keep]):
truths[int(q)].add(int(c))
# owner[c] -> the S1 that owns pool record c, over ALL ground truth, not just val
owner = dict(zip(t["gt_c"].tolist(), t["gt_q"].tolist()))
best, _ = F.tune_decision(va, truths, ids)
pred = F.predict_sets(va, best["threshold"], all_q=np.asarray(ids),
method=best["method"], miss_mass=best["miss_mass"])
m, _ = E.macro_f05(pred, truths, ids)
print(f"decision: {best['method']} F0.5 {m['f05']:.5f} "
f"P {m['precision']:.4f} R {m['recall']:.4f}\n")
fp = [(q, c) for q, cs in pred.items() for c in cs if c not in truths.get(q, ())]
n_pred = sum(len(v) for v in pred.values())
print(f"predicted {n_pred:,} pairs, {len(fp):,} false positives "
f"({len(fp)/max(n_pred,1):.2%})\n")
# who else was competing for each record, in OUR table
claim = collections.defaultdict(list)
for q, c, p in zip(va["q"].to_numpy(), va["c"].to_numpy(), va["p"].to_numpy()):
claim[int(c)].append((int(q), float(p)))
cat = collections.Counter()
rank_of_true = collections.Counter()
margins = []
examples = {"A": [], "B": [], "C": []}
for q, c in fp:
o = owner.get(c)
if o is None:
cat["C distractor (belongs to no S1)"] += 1
examples["C"].append((q, c, None))
continue
competitors = claim.get(c, [])
has_true = any(qq == o for qq, _ in competitors)
if has_true:
cat["A true owner WAS in our table (we chose wrong)"] += 1
ranked = sorted(competitors, key=lambda x: -x[1])
pos = [i for i, (qq, _) in enumerate(ranked) if qq == o]
rank_of_true[min(pos[0], 5) if pos else 99] += 1
pw = dict(competitors)
margins.append(pw[q] - pw[o])
examples["A"].append((q, c, o))
else:
cat["B true owner NOT in our table (retrieval miss)"] += 1
examples["B"].append((q, c, o))
print("=" * 74)
print("WHERE THE FALSE POSITIVES COME FROM")
print("=" * 74)
for k, v in cat.most_common():
print(f" {k:<48} {v:>7,} {v/max(len(fp),1):6.1%}")
if rank_of_true:
print("\n For group A, where did the TRUE owner rank among competitors?")
tot = sum(rank_of_true.values())
for r in sorted(rank_of_true):
lab = f"rank {r}" if r < 5 else ("rank 5+" if r < 99 else "not ranked")
print(f" {lab:<12} {rank_of_true[r]:>7,} {rank_of_true[r]/tot:6.1%}")
mg = np.array(margins)
print(f"\n Score margin by which the WRONG S1 beat the true owner:")
print(f" median {np.median(mg):.4f} p25 {np.percentile(mg,25):.4f} "
f"p75 {np.percentile(mg,75):.4f}")
print(f" within 0.05: {(mg < 0.05).mean():.1%} within 0.15: {(mg < 0.15).mean():.1%}")
print(" A small margin means the ordering is nearly right and a better")
print(" tie-break could flip it. A large one means the scorer is confident")
print(" and wrong, which needs features, not arbitration.")
print("\n" + "=" * 74)
print("WHAT THE FALSE POSITIVES LOOK LIKE")
print("=" * 74)
va_idx = {(int(q), int(c)): i for i, (q, c) in
enumerate(zip(va["q"].to_numpy(), va["c"].to_numpy()))}
ae = pool["addr_empty"].to_numpy()
ctry = s1["country"].to_numpy()
for grp in ("A", "B", "C"):
ex = examples[grp]
if not ex:
continue
qs = np.array([e[0] for e in ex])
cs = np.array([e[1] for e in ex])
print(f"\n group {grp}: {len(ex):,} empty-address {ae[cs].mean():.1%} "
f"by country {dict(collections.Counter(ctry[qs]).most_common())}")
for q, c, o in ex[:a.max_examples // 3]:
qn = s1['business_name'].iloc[q]
cn = pool['business_name'].iloc[c]
ca = pool['business_address'].iloc[c]
line = f" S1 {qn[:34]!r:38} -> {cn[:30]!r:34} | {str(ca)[:26]!r}"
if o is not None:
line += f" TRUE OWNER {s1['business_name'].iloc[o][:26]!r}"
print(line)
print("\n" + "=" * 74)
print("WHAT THIS MEANS")
print("=" * 74)
a_share = cat["A true owner WAS in our table (we chose wrong)"] / max(len(fp), 1)
b_share = cat["B true owner NOT in our table (retrieval miss)"] / max(len(fp), 1)
c_share = cat["C distractor (belongs to no S1)"] / max(len(fp), 1)
print(f" A {a_share:5.1%} fixable by better ASSIGNMENT (no new retrieval or scoring)")
print(f" B {b_share:5.1%} needs better RETRIEVAL for the true owner")
print(f" C {c_share:5.1%} needs a better SCORER or decoy features")
print(f"\n The 0.0041 of val loss splits roughly "
f"{0.0041*a_share:.4f} / {0.0041*b_share:.4f} / {0.0041*c_share:.4f}.")
if __name__ == "__main__":
main()