File size: 7,304 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
"""Step A. Mine administrative equivalences, and VALIDATE them where labels exist.

The validation is the whole reason this script is longer than the miner. France has no labels,
so a France-only change can never be checked directly - and the last France change made on
reasoning alone pointed the threshold in the wrong direction.

The honest substitute: the same generator produced US and India, the same swap appears there
(district vs state, county vs state), and those DO have labels. So the miner is run on all
three countries, and on US/India the mined features are scored against ground truth. If they
separate true pairs from false ones there, the France table is trustworthy for the same
reason. If they do not, the France table is discarded rather than shipped on faith.

Runs on CPU in a few minutes. No GPU, no model, no artifacts from any other pipeline.
"""
from __future__ import annotations

import argparse
import json
import os
import random
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 france_geo as G  # noqa: E402
from berx import paths as P  # noqa: E402


def load_prep(split: str):
    d = os.path.dirname(P.work("prep", split, "_"))
    s1 = pd.read_parquet(os.path.join(d, "source1.parquet"))
    pool = pd.read_parquet(os.path.join(d, "pool.parquet"))
    return s1, pool


def validate(s1: pd.DataFrame, pool: pd.DataFrame, gt_path: str, matcher: G.GeoMatcher,
             country: str, n_pos: int = 4000, seed: int = 42):
    """Do the mined features separate true pairs from hard false ones, on a labelled country?

    The negatives are deliberately HARD: for each sampled true pair, a different pool record
    of the same country whose name shares a token with the S1. Random negatives would be
    separated by the name alone and would tell us nothing about whether the geo features work.
    """
    from berx import textnorm as T

    gt = pd.read_csv(gt_path, sep="\t", dtype=str, keep_default_na=False, na_filter=False) \
        if gt_path.endswith(".tsv") else pd.read_parquet(gt_path)
    s1c = s1[s1["country"] == country]
    s1_idx = dict(zip(s1c["entity_id"], range(len(s1c))))
    s1a = dict(zip(s1c["entity_id"], s1c["business_address"]))
    s1n = dict(zip(s1c["entity_id"], s1c["business_name"]))

    poolc = pool[pool["country"] == country]
    pa = dict(zip(poolc["entity_id"], poolc["business_address"]))
    pn = dict(zip(poolc["entity_id"], poolc["business_name"]))

    tok_index: dict[str, list] = {}
    for eid, nm in pn.items():
        for t in set(T.tokens(T.norm_text(nm))):
            tok_index.setdefault(t, []).append(eid)

    rng = random.Random(seed)
    rows = []
    gt = gt[gt["source1_entity_id"].isin(s1_idx)]
    for _, r in gt.sample(min(n_pos, len(gt)), random_state=seed).iterrows():
        q = r["source1_entity_id"]
        mids = [x for x in str(r["matched_entity_ids"]).split(",") if x in pa]
        if not mids:
            continue
        c = rng.choice(mids)
        rows.append((s1a[q], pa[c], 1))
        cand = []
        for t in set(T.tokens(T.norm_text(s1n[q]))):
            cand += tok_index.get(t, [])[:50]
        cand = [x for x in cand if x not in set(mids)]
        if cand:
            rows.append((s1a[q], pa[rng.choice(cand)], 0))

    if not rows:
        return None
    F = pd.DataFrame([{**matcher.features(a, b), "y": y} for a, b, y in rows])
    rep = {}
    for c in G.FEATURE_NAMES:
        t, f = F[F.y == 1][c], F[F.y == 0][c]
        rep[c] = {"true_mean": round(float(t.mean()), 4),
                  "false_mean": round(float(f.mean()), 4),
                  "separation": round(float(t.mean() - f.mean()), 4)}
    # the headline check: does equiv beat exact at telling true from false?
    rep["_n"] = len(F)
    rep["_lift_equiv_over_exact"] = round(
        rep["geo_equiv"]["separation"] - rep["geo_exact"]["separation"], 4)
    return rep


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--split", default="test")
    ap.add_argument("--validate-on", default="train",
                    help="split that has ground truth, for the US/India sanity check")
    ap.add_argument("--min-support", type=int, default=8)
    ap.add_argument("--min-ratio", type=float, default=0.35)
    ap.add_argument("--skip-validate", action="store_true")
    a = ap.parse_args()

    s1, pool = load_prep(a.split)
    tables = {}
    for country in sorted(set(pool["country"])):
        sub = pool[pool["country"] == country]["business_address"]
        sub1 = s1[s1["country"] == country]["business_address"]
        print(f"\n== {country}: mining over {len(sub) + len(sub1):,} addresses")
        t = G.mine(list(sub) + list(sub1), min_support=a.min_support, min_ratio=a.min_ratio)
        n_pairs = sum(len(v) for v in t["equiv"].values()) // 2
        print(f"   admin names {t['n_admin_names']:,}   equivalences {n_pairs:,}")
        ex = [(k, sorted(v.items(), key=lambda kv: -kv[1])[:3])
              for k, v in list(t["equiv"].items())[:8]]
        for k, v in ex:
            print(f"     {k!r:32} ~ {[(x, s) for x, s in v]}")
        tables[country] = t

    out = P.work("geo", f"equiv_{a.split}.json")
    with open(out, "w", encoding="utf-8") as fh:
        json.dump(tables, fh, ensure_ascii=False)
    print(f"\nwrote {out}")

    if a.skip_validate:
        return
    print("\n" + "=" * 72)
    print("VALIDATION on labelled countries - does this help where we can check it?")
    print("=" * 72)
    s1t, poolt = load_prep(a.validate_on)
    gt = P.ground_truth(a.validate_on)
    report = {}
    for country in ("US", "India"):
        if country not in set(poolt["country"]):
            continue
        # validate with the table mined on the SAME split, or the check is contaminated by
        # the test pool having been used to build the thing being tested
        tt = G.mine(list(poolt[poolt["country"] == country]["business_address"]),
                    min_support=a.min_support, min_ratio=a.min_ratio)
        rep = validate(s1t, poolt, gt, G.GeoMatcher(tt), country)
        if rep:
            report[country] = rep
            print(f"\n  {country}  (n={rep['_n']:,})")
            for c in G.FEATURE_NAMES:
                r = rep[c]
                print(f"    {c:<16} true {r['true_mean']:>8.4f}  false {r['false_mean']:>8.4f}"
                      f"  sep {r['separation']:>+8.4f}")
            print(f"    -> equiv beats exact by {rep['_lift_equiv_over_exact']:+.4f}")

    ok = all(r["_lift_equiv_over_exact"] > 0.002 for r in report.values()) and report
    print("\n" + ("PASS - the equivalence table adds separation on labelled countries, so the"
                  "\n       France table is worth shipping as features."
                  if ok else
                  "FAIL - equiv does not beat exact where we can check it. Do NOT ship the"
                  "\n       France table; the swap is either rarer or differently shaped than"
                  "\n       assumed, and shipping it on reasoning alone is how the last France"
                  "\n       change went in backwards."))
    with open(P.work("geo", "validation.json"), "w") as fh:
        json.dump(report, fh, indent=1)


if __name__ == "__main__":
    main()