amlc-work / code /src /metric.py
Arushhh's picture
code snapshot
0dd5490 verified
Raw History Blame Contribute Delete
12.4 kB
"""Challenge metric for AMLC 2026 business entity resolution.
Per S1 entity, with prediction set S and truth set T:
T empty, S empty -> 1.0
T empty, S non-empty -> 0.0
T non-empty, S empty -> 0.0
otherwise P = |S&T|/|S|, R = |S&T|/|T|, F = 1.25*P*R / (0.25*P + R),
and 0.0 when |S&T| = 0.
The leaderboard score is the macro average of F over all S1 entities in the
truth file (a missing prediction counts as the empty set).
Note: with tp = |S&T|, k = |S|, n = |T| the formula reduces to
F = 5*tp / (4*k + n), which is what src/decode.py optimises.
CLI:
python -m src.metric --pred matching_results.tsv --truth train_ground_truth.tsv \
[--groups s1.tsv [--group-col country]]
"""
from __future__ import annotations
import argparse
import csv
import sys
from typing import Iterable, Mapping
import numpy as np
import pandas as pd
__all__ = [
"f05_entity",
"entity_scores",
"macro_f05",
"read_id_list_tsv",
"write_id_list_tsv",
"read_groups",
"breakdown",
]
ID_COL = "source1_entity_id"
LIST_COLS = ("matched_entity_ids", "candidate_entity_ids")
_EMPTY: frozenset = frozenset()
# ---------------------------------------------------------------------------
# Per-entity score
# ---------------------------------------------------------------------------
def f05_entity(pred: set, true: set) -> float:
"""F0.5 for one S1 entity, with the exact challenge edge rules."""
if not true:
return 0.0 if pred else 1.0
if not pred:
return 0.0
if not isinstance(pred, (set, frozenset)):
pred = set(pred)
if not isinstance(true, (set, frozenset)):
true = set(true)
tp = len(pred & true)
if tp == 0:
return 0.0
p = tp / len(pred)
r = tp / len(true)
return 1.25 * p * r / (0.25 * p + r)
def _prf(pred: set, true: set) -> tuple[float, float, float, int]:
"""(F0.5, precision or nan, recall or nan, tp) for one entity.
Precision is nan when pred is empty, recall is nan when true is empty.
"""
f = f05_entity(pred, true)
if pred and true:
if isinstance(pred, (set, frozenset)) and isinstance(true, (set, frozenset)):
tp = len(pred & true)
else:
tp = len(set(pred) & set(true))
else:
tp = 0
prec = tp / len(pred) if pred else np.nan
rec = tp / len(true) if true else np.nan
return f, prec, rec, tp
def entity_scores(pred: Mapping[str, set], truth: Mapping[str, set]) -> pd.DataFrame:
"""One row per truth key: f05, precision, recall, tp, n_pred, n_true.
Keys missing from ``pred`` are scored as empty predictions; keys present
only in ``pred`` are ignored (the score is defined over the truth file).
"""
keys = list(truth.keys())
n = len(keys)
f = np.empty(n)
prec = np.empty(n)
rec = np.empty(n)
tp = np.empty(n, dtype=np.int32)
n_pred = np.empty(n, dtype=np.int32)
n_true = np.empty(n, dtype=np.int32)
get = pred.get
for i, key in enumerate(keys):
t = truth[key]
s = get(key, _EMPTY)
f[i], prec[i], rec[i], tp[i] = _prf(s, t)
n_pred[i] = len(s)
n_true[i] = len(t)
return pd.DataFrame(
{"f05": f, "precision": prec, "recall": rec, "tp": tp, "n_pred": n_pred, "n_true": n_true},
index=pd.Index(keys, name=ID_COL),
)
def macro_f05(pred: Mapping[str, set], truth: Mapping[str, set]) -> float:
"""Macro F0.5 averaged over ALL keys of ``truth`` (missing pred = empty)."""
if not truth:
return float("nan")
get = pred.get
total = 0.0
for key, t in truth.items():
total += f05_entity(get(key, _EMPTY), t)
return total / len(truth)
# ---------------------------------------------------------------------------
# I/O
# ---------------------------------------------------------------------------
def _clean(tok: str) -> str:
tok = tok.strip()
if len(tok) >= 2 and tok[0] == tok[-1] and tok[0] in "\"'":
tok = tok[1:-1].strip()
return tok
def _parse_list(field: str) -> set:
field = _clean(field)
if not field:
return set()
if field[0] == "[" and field[-1] == "]": # tolerate python-list style
field = field[1:-1]
out = set()
for tok in field.split(","):
tok = _clean(tok)
if tok:
out.add(sys.intern(tok))
return out
def read_id_list_tsv(path) -> dict[str, set]:
"""Read a challenge TSV ``source1_entity_id<TAB>matched_entity_ids``.
The header's second column may also be ``candidate_entity_ids``. The second
column is a comma-separated list and may be empty or missing. Streams line
by line; repeated S1 ids are unioned. Candidate ids are interned so that ids
shared across rows are stored once.
"""
out: dict[str, set] = {}
with open(path, "r", encoding="utf-8", newline="") as fh:
first = fh.readline()
if not first:
return out
head = [_clean(c).lower() for c in first.rstrip("\r\n").split("\t")]
is_header = head[0] == ID_COL or (len(head) > 1 and head[1] in LIST_COLS)
lines: Iterable[str] = fh
if not is_header:
lines = _chain_first(first, fh)
for line in lines:
line = line.rstrip("\r\n")
if not line.strip():
continue
key, sep, rest = line.partition("\t")
key = _clean(key)
if not key:
continue
vals = _parse_list(rest) if sep else set()
cur = out.get(key)
if cur is None:
out[key] = vals
else:
cur |= vals
return out
def _chain_first(first: str, fh):
yield first
yield from fh
def write_id_list_tsv(pred: Mapping[str, Iterable[str]], path, all_ids: Iterable[str] | None = None,
list_col: str = "matched_entity_ids") -> None:
"""Write ``pred`` in the challenge format. ``all_ids`` (if given) fixes the
row set/order; ids with no prediction get an empty second column."""
keys = list(all_ids) if all_ids is not None else list(pred.keys())
get = pred.get
with open(path, "w", encoding="utf-8", newline="") as fh:
fh.write(f"{ID_COL}\t{list_col}\n")
for key in keys:
vals = get(key) or ()
fh.write(f"{key}\t{','.join(map(str, vals))}\n")
def read_groups(path, group_col: str = "country", id_col: str | None = None) -> dict[str, str]:
"""Map S1 id -> group label from a TSV/CSV (e.g. the S1 entity file).
Only the id and group columns are loaded. The id column defaults to
``source1_entity_id``, then ``entity_id``, then the first column.
"""
with open(path, "r", encoding="utf-8") as fh:
header = fh.readline().rstrip("\r\n")
sep = "\t" if "\t" in header else ","
cols = [_clean(c) for c in header.split(sep)]
if id_col is None:
lower = [c.lower() for c in cols]
for cand in (ID_COL, "entity_id", "id"):
if cand in lower:
id_col = cols[lower.index(cand)]
break
else:
id_col = cols[0]
if group_col not in cols:
raise ValueError(f"group column {group_col!r} not in {path}; columns: {cols}")
# TSV: no quote processing, so stray quotes in free-text columns (names,
# addresses) cannot swallow lines; ids/labels are unquoted afterwards.
quoting = csv.QUOTE_NONE if sep == "\t" else csv.QUOTE_MINIMAL
df = pd.read_csv(path, sep=sep, usecols=[id_col, group_col], dtype=str,
keep_default_na=False, quoting=quoting)
ids = [_clean(x) for x in df[id_col].tolist()]
labs = [_clean(x) for x in df[group_col].tolist()]
return dict(zip(ids, labs))
# ---------------------------------------------------------------------------
# Breakdown
# ---------------------------------------------------------------------------
_BUCKETS = ["0", "1", "2", "3", "4", "5+"]
def _summarise(g: pd.DataFrame, total_loss: float, n_total: int) -> dict:
single = g["n_true"].to_numpy() == 0
loss = float((1.0 - g["f05"]).sum())
return {
"n": len(g),
"share": len(g) / n_total if n_total else np.nan,
"macro_f05": float(g["f05"].mean()) if len(g) else np.nan,
# precision averaged over entities with a non-empty prediction,
# recall averaged over entities with a non-empty truth set
"mean_precision": float(np.nanmean(g["precision"])) if g["precision"].notna().any() else np.nan,
"mean_recall": float(np.nanmean(g["recall"])) if g["recall"].notna().any() else np.nan,
"n_singleton": int(single.sum()),
# fraction of truth-empty entities predicted empty
"singleton_acc": float((g["n_pred"].to_numpy()[single] == 0).mean()) if single.any() else np.nan,
"pred_empty_rate": float((g["n_pred"] == 0).mean()) if len(g) else np.nan,
"mean_n_pred": float(g["n_pred"].mean()) if len(g) else np.nan,
"mean_n_true": float(g["n_true"].mean()) if len(g) else np.nan,
# share of the total (1 - F) loss that this slice accounts for
"loss_share": loss / total_loss if total_loss > 0 else 0.0,
}
def breakdown(pred: Mapping[str, set], truth: Mapping[str, set],
groups: Mapping[str, str] | None = None,
scores: pd.DataFrame | None = None) -> pd.DataFrame:
"""Per-slice diagnostics.
Rows: ``overall``; one per group label (if ``groups`` is given; S1 ids not in
``groups`` go to ``<missing>``); one per true-match-count bucket
(0,1,2,3,4,5+). Columns: n, share, macro_f05, mean_precision, mean_recall,
n_singleton, singleton_acc, pred_empty_rate, mean_n_pred, mean_n_true,
loss_share. The first two index levels are (dimension, slice).
"""
s = entity_scores(pred, truth) if scores is None else scores
n_total = len(s)
total_loss = float((1.0 - s["f05"]).sum())
rows: list[tuple[str, str, dict]] = [("overall", "all", _summarise(s, total_loss, n_total))]
if groups is not None:
glab = pd.Series([groups.get(k, "<missing>") for k in s.index], index=s.index)
order = glab.value_counts().index
for lab in order:
rows.append(("group", str(lab), _summarise(s[glab.to_numpy() == lab], total_loss, n_total)))
bucket = np.minimum(s["n_true"].to_numpy(), 5)
for b in range(6):
sub = s[bucket == b]
if len(sub):
rows.append(("true_count", _BUCKETS[b], _summarise(sub, total_loss, n_total)))
idx = pd.MultiIndex.from_tuples([(d, v) for d, v, _ in rows], names=["dimension", "slice"])
return pd.DataFrame([r for _, _, r in rows], index=idx)
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description="Macro F0.5 for AMLC 2026 entity resolution")
ap.add_argument("--pred", required=True, help="matching_results.tsv")
ap.add_argument("--truth", required=True, help="ground-truth TSV in the same format")
ap.add_argument("--groups", default=None, help="TSV/CSV with S1 id + group column (e.g. s1.tsv)")
ap.add_argument("--group-col", default="country")
ap.add_argument("--id-col", default=None, help="id column in --groups file (auto-detected)")
args = ap.parse_args(argv)
truth = read_id_list_tsv(args.truth)
pred = read_id_list_tsv(args.pred)
extra = sum(1 for k in pred if k not in truth)
missing = sum(1 for k in truth if k not in pred)
groups = read_groups(args.groups, args.group_col, args.id_col) if args.groups else None
scores = entity_scores(pred, truth)
print(f"truth entities: {len(truth):,} pred rows: {len(pred):,} "
f"truth ids missing from pred (scored as empty): {missing:,} "
f"pred ids not in truth (ignored): {extra:,}")
print(f"macro F0.5 = {scores['f05'].mean():.6f}")
bd = breakdown(pred, truth, groups, scores=scores)
with pd.option_context("display.max_rows", 500, "display.max_columns", None, "display.width", 250,
"display.float_format", "{:.4f}".format):
print(bd)
return 0
if __name__ == "__main__":
raise SystemExit(main())