PopTurk / code /berx /structure.py
Jyo-K's picture
Upload folder using huggingface_hub
d231962 verified
Raw
History Blame Contribute Delete
14.5 kB
"""B. Competitive and structural features over a scored candidate table.
THE POINT. Every scorer in this pipeline reads one pair at a time. It is asked "do these two
strings describe the same business" when the question the metric actually rewards is "which
S1 owns this record". Those differ whenever a record is weakly similar to one S1 and weakly
similar to nothing else: the pairwise view says reject, the ownership view says it is forced.
The measurement that settles it, on empty-address candidates with an exact core-name match:
competitors TP FP ratio (break-even at the shipped operating point
1 (forced) 306 24 12.75 is 3.76:1, not 4:1 - the 4:1 figure is the
2 110 176 0.62 TP -> T limit, and quoting it here would
11+ 177 9,230 0.02 reject pairs that are worth taking)
aggregated 442 3,074 0.14
The aggregate is what a pair-level test reports, and it is 27x below break-even, which is why
an earlier pass concluded these pairs were unrecoverable. Splitting by competitor count shows
a subset three times above break-even. None of that is visible without global information.
CAVEAT ON THE SOURCE NUMBERS. Those counts came from `val_scored_20000.parquet`, which was
drawn with `RandomState(42)` where the split used `default_rng(42)`. It is therefore not the
intended val split but a random draw over all train S1, roughly 7% of it seen during
cross-encoder or stacker training. Ratios between groups survive that; the absolute level
does not. Re-measure on a clean split before trusting a threshold picked from it.
"""
from __future__ import annotations
import numpy as np
import pandas as pd
from . import textnorm as T
# --------------------------------------------------------------------------- measured recipe
# The six name-sharing features, reproduced EXACTLY as specified and measured in
# MODEL5_FALSE_NEGATIVE_FIXES.md §3.1. Retraining model-4's stage-2 LightGBM with these and
# nothing else changed gave, on the same stack split, same 5 folds, same seeds:
#
# stack out-of-fold plain val
# model-4 0.98248 0.98298
# + these six 0.98543 (+0.0030) 0.98621 (+0.0032)
#
# This is a reproduction, not an interpretation. My own earlier feature set overlapped it but
# was missing the two HIGHEST-gain members - x_n_s1_own_name (gain rank 4 of 79) and
# x_n_s1_cand_name_ns (rank 7) - and left the counts unclipped. Both matter:
# * x_n_s1_own_name asks how common THIS S1's own name is. It is the strongest of the six,
# and no feature I had captured it at all: everything I wrote looked at the candidate.
# * the clip at 10 stops a handful of enormous name groups from dominating tree splits.
# Keep all six even though the first three rank low alone; the measurement used all six.
NAME_FEATURES = ["x_empty", "x_name_eq", "x_name_ns_eq",
"x_n_s1_cand_name", "x_n_s1_cand_name_ns", "x_n_s1_own_name"]
def _name_core(s: str) -> str:
return T.split_legal_suffix(T.norm_text(str(s)))[0]
def _name_ns(core: str) -> str:
"""name_core with no spaces. norm_text has already removed punctuation."""
return core.replace(" ", "")
def name_key_columns(df: pd.DataFrame, name_col: str = "business_name") -> pd.DataFrame:
"""Add name_core / name_ns to a prepared source table."""
core = [_name_core(x) for x in df[name_col].astype(str)]
return pd.DataFrame({"name_core": core, "name_ns": [_name_ns(x) for x in core]},
index=df.index)
def name_features(d: pd.DataFrame, s1: pd.DataFrame, pool: pd.DataFrame,
qcol: str = "q", ccol: str = "c") -> pd.DataFrame:
"""The six features for candidate rows `d`, indexing into `s1` and `pool`.
`s1` and `pool` must already carry name_core / name_ns (see name_key_columns), and
`pool` must carry addr_empty.
COUNTS ARE OVER THE SPLIT'S OWN S1 TABLE - all 2,206,821 on train, all 1,732,544 on test,
every country including France. Reusing train counts on test would be a different feature.
Country enters only as a string key for grouping, never as a value, so France gets its own
counts automatically and the open-set rule is respected.
"""
ctry = s1["country"].to_numpy()[d[qcol].to_numpy()]
a = s1["name_core"].to_numpy()[d[qcol].to_numpy()]
b = pool["name_core"].to_numpy()[d[ccol].to_numpy()]
ans = s1["name_ns"].to_numpy()[d[qcol].to_numpy()]
bns = pool["name_ns"].to_numpy()[d[ccol].to_numpy()]
cn = (s1["country"].astype(str) + "\t" + s1["name_core"].astype(str)).value_counts()
cns = (s1["country"].astype(str) + "\t" + s1["name_ns"].astype(str)).value_counts()
f = pd.DataFrame(index=d.index)
f["x_empty"] = pool["addr_empty"].to_numpy()[d[ccol].to_numpy()].astype(np.float32)
f["x_name_eq"] = (a == b).astype(np.float32)
f["x_name_ns_eq"] = (ans == bns).astype(np.float32)
f["x_n_s1_cand_name"] = pd.Series(ctry + "\t" + b).map(cn).fillna(0) \
.clip(upper=10).to_numpy().astype(np.float32)
f["x_n_s1_cand_name_ns"] = pd.Series(ctry + "\t" + bns).map(cns).fillna(0) \
.clip(upper=10).to_numpy().astype(np.float32)
f["x_n_s1_own_name"] = pd.Series(ctry + "\t" + a).map(cn).fillna(0) \
.clip(upper=10).to_numpy().astype(np.float32)
return f
FEATURE_NAMES = [
"n_claimants", "rev_rank", "rev_rank_frac", "is_best_s1", "gap_to_best_other",
"gap_to_second", "mutual_topk", "fwd_rank", "cand_addr_empty", "name_overlap",
"scrambled", "n_competitors_exact_name", "is_unique_name_owner",
"sibling_same_name", "s1_cand_count", "p_minus_s1_max",
"name_core_equal", "empty_and_unique_name", "empty_and_shared_name", "name_is_other_s1",
]
# --------------------------------------------------------------------------- global name map
def build_name_index(s1: pd.DataFrame, name_col: str = "business_name",
country_col: str = "country") -> dict:
"""How many S1 entities carry each (core name, country)?
Built over EVERY S1 row, not over a validation slice. A competitor can be anywhere in the
data, so restricting this to a sample silently inflates the uniqueness rate and the
forced-assignment group with it.
"""
keys = [T.split_legal_suffix(T.norm_text(n))[0] + "\x00" + T.norm_country(c)
for n, c in zip(s1[name_col].astype(str), s1[country_col].astype(str))]
vc = pd.Series(keys).value_counts()
return {"key_by_row": keys, "count": vc.to_dict()}
def core_key(name: str, country: str) -> str:
return T.split_legal_suffix(T.norm_text(name))[0] + "\x00" + T.norm_country(country)
# --------------------------------------------------------------------------- pair features
def add_features(cand: pd.DataFrame, s1_name: np.ndarray, s1_country: np.ndarray,
pool_name: np.ndarray, pool_addr: np.ndarray, pool_country: np.ndarray,
name_count: dict, qcol: str = "q", ccol: str = "c", pcol: str = "p",
topk: int = 10, s1_key: dict | None = None,
progress: bool = True) -> pd.DataFrame:
"""Attach every feature in FEATURE_NAMES to a scored candidate table.
`cand` needs integer row indices into the S1 and pool arrays, plus a score. The arrays are
positional, matching raw source order - the same contract the embedding matrices use.
Everything is computed with sorts and groupby reductions rather than per-row Python, so a
24M-row test table stays inside a few minutes and a few GB.
"""
df = cand
q = df[qcol].to_numpy()
c = df[ccol].to_numpy()
p = df[pcol].to_numpy(dtype=np.float32)
n = len(df)
out = {}
# S1 core keys, again only for the rows referenced.
s1_core_key = s1_key if s1_key is not None else {}
# ---- competition for the RECORD: sort by (c, -p) once and reduce within each record
order = np.lexsort((-p, c))
c_s, p_s = c[order], p[order]
# group boundaries
new = np.empty(n, dtype=bool)
new[0] = True
np.not_equal(c_s[1:], c_s[:-1], out=new[1:])
gid = np.cumsum(new) - 1
n_groups = gid[-1] + 1 if n else 0
starts = np.flatnonzero(new)
sizes = np.diff(np.append(starts, n))
rank_in_group = np.arange(n) - starts[gid] # 0 = best for this record
n_claim = sizes[gid]
best_p = p_s[starts][gid]
second = np.where(sizes[gid] > 1, p_s[np.minimum(starts[gid] + 1, n - 1)], np.nan)
# gap to the best OTHER S1: for the leader that is the runner-up, otherwise the leader
gap_other = np.where(rank_in_group == 0, p_s - np.nan_to_num(second, nan=0.0), p_s - best_p)
inv = np.empty(n, dtype=np.int64)
inv[order] = np.arange(n)
out["rev_rank"] = rank_in_group[inv].astype(np.int32)
out["n_claimants"] = n_claim[inv].astype(np.int32)
out["is_best_s1"] = (out["rev_rank"] == 0).astype(np.int8)
out["gap_to_best_other"] = gap_other[inv].astype(np.float32)
out["gap_to_second"] = (p_s - np.nan_to_num(second, nan=0.0))[inv].astype(np.float32)
out["rev_rank_frac"] = (out["rev_rank"] / np.maximum(out["n_claimants"] - 1, 1)).astype(np.float32)
# ---- competition for the S1 SIDE: same reduction with the roles swapped
order2 = np.lexsort((-p, q))
q_s2, p_s2 = q[order2], p[order2]
new2 = np.empty(n, dtype=bool)
new2[0] = True
np.not_equal(q_s2[1:], q_s2[:-1], out=new2[1:])
gid2 = np.cumsum(new2) - 1
starts2 = np.flatnonzero(new2)
sizes2 = np.diff(np.append(starts2, n))
fwd_rank = np.arange(n) - starts2[gid2]
s1_max = p_s2[starts2][gid2]
inv2 = np.empty(n, dtype=np.int64)
inv2[order2] = np.arange(n)
out["fwd_rank"] = fwd_rank[inv2].astype(np.int32)
out["s1_cand_count"] = sizes2[gid2][inv2].astype(np.int32)
out["p_minus_s1_max"] = (p_s2 - s1_max)[inv2].astype(np.float32)
# mutual top-k: the record is in this S1's top-k AND this S1 is in the record's top-k.
# A mutual nearest-neighbour is the cheapest available proxy for "these two chose each
# other", and it is the one competitive signal that costs no extra inference at all.
out["mutual_topk"] = ((out["fwd_rank"] < topk) & (out["rev_rank"] < topk)).astype(np.int8)
# ---- record-side text structure
addr_empty = np.array([not str(a).strip() for a in pool_addr], dtype=np.int8)
out["cand_addr_empty"] = addr_empty[c]
# Token sets are built ONLY for the rows a candidate actually references. Building them
# for all 1.7M S1 and 10M pool rows costs tens of GB of Python set objects, most of which
# no pair ever touches.
uq = np.unique(q)
uc = np.unique(c)
q_tok = {int(i): set(T.tokens(T.norm_text(str(s1_name[i])))) for i in uq}
c_tok = {int(i): set(T.tokens(T.norm_text(str(pool_name[i])))) for i in uc}
ov = np.empty(n, dtype=np.float32)
step = max(1, n // 10)
for i in range(n):
if progress and i % step == 0 and i:
print(f" name_overlap {i:>12,}/{n:,} ({i/n:5.1%})", flush=True)
a, b = q_tok[int(q[i])], c_tok[int(c[i])]
inter = len(a & b)
u = len(a) + len(b) - inter
ov[i] = (inter / u) if u else 0.0
out["name_overlap"] = ov
# "scrambled" is the generator's made-up-word rewrite (Zephveo, Drexdelta): 2.4% of US
# copies and 7.0% of India's, and 18% of model-4's val loss. A decoy almost never has one.
out["scrambled"] = (ov == 0.0).astype(np.int8)
# ---- global uniqueness of the RECORD name among all S1
# This is the measurement the whole track rests on. Calibration on model-4's stack,
# restricted to empty-address candidates whose name_core equals this S1's:
#
# unique among the country's S1 9,171 pairs mean p 0.714 ACTUAL match rate 0.982
# shared by 2 S1 3,488 mean p 0.565 actual 0.525
# shared by 3 or more 20,972 mean p 0.280 actual 0.170
#
# The unique group is under-predicted by 0.27 in probability. Per coarse group the model
# is perfectly calibrated, which is why ordinary calibration checks never found this: the
# error only appears once you condition on a competitor count the model cannot see.
ckey = {int(i): core_key(str(pool_name[i]), str(pool_country[i])) for i in uc}
if not s1_core_key:
s1_core_key = {int(i): core_key(str(s1_name[i]), str(s1_country[i])) for i in uq}
ncomp_by_c = {i: name_count.get(k, 0) for i, k in ckey.items()}
ncomp = np.fromiter((ncomp_by_c[int(x)] for x in c), np.int32, n)
out["n_competitors_exact_name"] = ncomp
out["is_unique_name_owner"] = (ncomp == 1).astype(np.int8)
# ---- sibling agreement: has this S1 already got a strong candidate with the same name?
# 55% of rejected empty-address true pairs have a correctly matched sibling with the same
# name, so this is the feature that lets one confident sibling carry an unconfident one.
sib = np.zeros(n, dtype=np.int8)
strong = p >= 0.5
have = {(int(q[i]), ckey[int(c[i])]) for i in np.flatnonzero(strong)}
if have:
for i in np.flatnonzero(~strong):
if (int(q[i]), ckey[int(c[i])]) in have:
sib[i] = 1
out["sibling_same_name"] = sib
# ---- the exact structural group the calibration table above is indexed by
if progress:
print(f" name_core_equal over {n:,} rows", flush=True)
same_core = np.fromiter(
(1 if ckey[int(c[i])] == s1_core_key[int(q[i])] else 0 for i in range(n)), np.int8, n)
out["name_core_equal"] = same_core
out["empty_and_unique_name"] = (
(out["cand_addr_empty"] == 1) & (same_core == 1) & (ncomp == 1)).astype(np.int8)
out["empty_and_shared_name"] = (
(out["cand_addr_empty"] == 1) & (same_core == 1) & (ncomp >= 3)).astype(np.int8)
# The record's name matches SOME S1 exactly, but not this one - a decoy signature. 22.5%
# of distractors reuse a real S1 name, and these score about 0.05 against a mean p of 0.18.
out["name_is_other_s1"] = ((same_core == 0) & (ncomp >= 1)).astype(np.int8)
for k in FEATURE_NAMES:
df[k] = out[k]
return df