| """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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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",
|
| ]
|
|
|
|
|
|
|
|
|
| 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)
|
|
|
|
|
|
|
|
|
| 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_key = s1_key if s1_key is not None else {}
|
|
|
|
|
| order = np.lexsort((-p, c))
|
| c_s, p_s = c[order], p[order]
|
|
|
| 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]
|
| 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_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)
|
|
|
|
|
| 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)
|
|
|
|
|
|
|
|
|
| out["mutual_topk"] = ((out["fwd_rank"] < topk) & (out["rev_rank"] < topk)).astype(np.int8)
|
|
|
|
|
| addr_empty = np.array([not str(a).strip() for a in pool_addr], dtype=np.int8)
|
| out["cand_addr_empty"] = addr_empty[c]
|
|
|
|
|
|
|
|
|
| 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
|
|
|
|
|
| out["scrambled"] = (ov == 0.0).astype(np.int8)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
|
|
|
|
|
|
|
|
| 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
|
|
|
|
|
| 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)
|
|
|
|
|
| out["name_is_other_s1"] = ((same_core == 0) & (ncomp >= 1)).astype(np.int8)
|
|
|
| for k in FEATURE_NAMES:
|
| df[k] = out[k]
|
| return df
|
|
|