Download code/analyses.py from citead/geo-citation-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 7.8 kB
-
https://huggingface.co/datasets/citead/geo-citation-benchmark/resolve/main/code/analyses.py
- Command line
-
hf download hf://datasets/citead/geo-citation-benchmark/code/analyses.py
-
curl -L -o analyses.py https://huggingface.co/datasets/citead/geo-citation-benchmark/resolve/main/code/analyses.py
7.8 kB
| """Analyses added for the paper: cross-engine agreement, trivial baselines, top-1 and its chance level, | |
| per-engine and per-query means, position combination, overlap check. Usage: python code/analyses.py <archive root>. | |
| Writes results/analyses/extra_analyses.json. | |
| Reuses reproduce_tables.py (same Spearman, same query-clustered bootstrap, seed 88).""" | |
| import collections, glob, json, os, sys | |
| import numpy as np | |
| A = sys.argv[1] | |
| OUT = A + "/results/analyses/extra_analyses.json" | |
| PREV = json.load(open(OUT)) if os.path.exists(OUT) else {} | |
| sys.path.insert(0, A + "/code") | |
| import reproduce_tables as R | |
| lab = R.labels() | |
| P = A + "/benchmark/predictions/" | |
| SC = {"jev_listwise": "judges/jev_1.13_listwise", "jev_pointwise": "judges/jev_1.13_pointwise", | |
| "jev27b": "open_decision_models/jev27b_listwise", "pplx27b": "open_decision_models/pplx27b_listwise", | |
| "jev9b": "open_decision_models/jev9b_listwise", "student4b_s42": "students/student_4b_s42", | |
| "student4b_ens3": "students/student_4b_ensemble3", "student06_s42": "students/student_0.6b_s42", | |
| "qwen_rr4b_zs": "zero_shot/qwen3_reranker_4b", "nim_zs": "zero_shot/nim_reranker_by_group"} | |
| f = {k: R.load_scorer(P + v + ".json") for k, v in SC.items()} | |
| rho = {k: R.per_group(lab, s) for k, s in f.items()} | |
| out = {} | |
| r3 = lambda t: [round(x, 4) for x in t[:3]] + [t[3]] | |
| # 1. Cross-engine agreement: other engines' mean label on the same query | |
| byq = collections.defaultdict(dict) | |
| for g, l in lab.items(): | |
| e, q = g.split("::", 1); byq[q][e] = l | |
| def loo(g, s): | |
| e, q = g.split("::", 1) | |
| o = [byq[q][x][s] for x in byq[q] if x != e] | |
| return sum(o) / len(o) if o else None | |
| cons = R.per_group(lab, loo) | |
| out["consensus"] = r3(R.boot(cons)) | |
| for k in ("jev_listwise", "jev27b", "student4b_s42", "student4b_ens3"): | |
| sub = {g: rho[k][g] for g in cons} | |
| out[f"{k}_on_consensus_groups"] = r3(R.boot(sub)) | |
| out[f"consensus_minus_{k}"] = r3(R.paired(cons, rho[k])) | |
| # 2. Trivial baselines | |
| txt = {} | |
| for l in open(A + "/benchmark/passages.jsonl"): | |
| r = json.loads(l); txt[(r["query"], r["src_idx"])] = r["text"].lower().split() | |
| N = len(txt); avg = sum(map(len, txt.values())) / N | |
| df = collections.Counter(w for d in txt.values() for w in set(d)) | |
| def bm25(g, s, k1=1.2, b=0.75): | |
| q = g.split("::", 1)[1]; d = txt[(q, s)]; tf = collections.Counter(d); sc = 0.0 | |
| for w in set(q.lower().split()): | |
| if w in tf: | |
| sc += np.log(1 + (N - df[w] + .5) / (df[w] + .5)) * tf[w] * (k1 + 1) / (tf[w] + k1 * (1 - b + b * len(d) / avg)) | |
| return sc | |
| base = {"position": lambda g, s: -s, "bm25": bm25, "length": lambda g, s: len(txt[(g.split("::", 1)[1], s)])} | |
| for k, fn in base.items(): | |
| out[f"baseline_{k}"] = r3(R.boot(R.per_group(lab, fn))) | |
| pos_mean = collections.defaultdict(list) | |
| for g, l in lab.items(): | |
| for s, v in l.items(): pos_mean[s].append(v) | |
| out["mean_label_by_position"] = {s: round(float(np.mean(v)), 4) for s, v in sorted(pos_mean.items())} | |
| # 3. Top-1 accuracy (prediction's top source is a most-cited source) | |
| def top1(fn): | |
| h = {} | |
| for g, l in lab.items(): | |
| y = [l[s] for s in sorted(l)] | |
| if max(y) == min(y): continue | |
| p = [fn(g, s) for s in sorted(l)] | |
| if any(v is None for v in p): continue | |
| h[g] = float(y[int(np.argmax(p))] == max(y)) | |
| return h | |
| out["top1"] = {k: r3(R.boot(top1(fn))) for k, fn in list(f.items()) + [("position", base["position"])]} | |
| # 4. Per-engine macro average | |
| eng = collections.defaultdict(lambda: collections.defaultdict(list)) | |
| for k in SC: | |
| for g, v in rho[k].items(): eng[k][g.split("::")[0]].append(v) | |
| out["per_engine"] = {k: {e: [round(float(np.mean(v)), 4), len(v)] for e, v in sorted(d.items())} for k, d in eng.items()} | |
| out["macro_over_engines"] = {k: round(float(np.mean([np.mean(v) for v in d.values()])), 4) for k, d in eng.items()} | |
| # 5. Score + source position, weight fitted on four folds, applied to the fifth | |
| folds = json.load(open(A + "/benchmark/folds_query.json")) | |
| def ranks5(x): | |
| return R.ranks(x) | |
| def combo(fn, w): | |
| def g_(g, s): | |
| sis = sorted(lab[g]); p = [fn(g, t) for t in sis] | |
| if any(v is None for v in p): return None | |
| return ranks5(p)[sis.index(s)] + w * (4 - s) | |
| return g_ | |
| W = [0, .1, .2, .3, .5, .75, 1, 1.5, 2, 3] | |
| for k in ("student4b_s42", "jev_listwise"): | |
| pre = {w: R.per_group(lab, combo(f[k], w)) for w in W} | |
| oof, chosen = {}, [] | |
| for fo in range(5): | |
| tr = lambda g: folds[g.split("::", 1)[1]] != fo | |
| best = max(W, key=lambda w: np.mean([v for g, v in pre[w].items() if tr(g)])) | |
| chosen.append(best) | |
| oof.update({g: v for g, v in pre[best].items() if not tr(g)}) | |
| out[f"{k}_plus_position_oof"] = {"rho": r3(R.boot(oof)), "weights": chosen, | |
| "gain": r3(R.paired(oof, rho[k]))} | |
| # 7. Cross-engine agreement excluding engines of the same vendor | |
| VEND = {"gpt": "openai", "openai": "openai", "gemini": "google", "google": "google", "mistralai": "mistral", | |
| "qwen": "qwen", "meta": "meta", "nex-agi": "nex"} | |
| vend = lambda e: VEND[e.split("/")[0] if "/" in e else e.split("-")[0]] | |
| def loo_v(g, s): | |
| e, q = g.split("::", 1) | |
| o = [byq[q][x][s] for x in byq[q] if vend(x) != vend(e)] | |
| return sum(o) / len(o) if o else None | |
| cv = R.per_group(lab, loo_v) | |
| out["consensus_other_vendors"] = r3(R.boot(cv)) | |
| out["consensus_other_vendors_minus_jev_listwise"] = r3(R.paired(cv, rho["jev_listwise"])) | |
| out["consensus_other_vendors_minus_student4b_s42"] = r3(R.paired(cv, rho["student4b_s42"])) | |
| json.dump(out, open(OUT, "w"), indent=1) | |
| print({k: out[k] for k in out if k.startswith("consensus_other")}) | |
| # 8. Agreement between the two teachers (0.759): computed on teacher labels, which are not redistributed | |
| out["teacher_agreement"] = PREV.get("teacher_agreement") | |
| # 9. Per-query mean (each query weighted once) and chance level of top-1 | |
| pq = {} | |
| for k in SC: | |
| byq_r = collections.defaultdict(list) | |
| for g, v in rho[k].items(): | |
| byq_r[g.split("::", 1)[1]].append(v) | |
| pq[k] = round(float(np.mean([np.mean(v) for v in byq_r.values()])), 4) | |
| out["per_query_mean"] = pq | |
| ch = [sum(1 for v in l.values() if v == max(l.values())) / 5 for g, l in lab.items() if len(set(l.values())) > 1] | |
| out["top1_chance"] = round(float(np.mean(ch)), 4) | |
| # 10. Overlap: evaluation passages whose first 40 words also open a training source | |
| key40 = lambda t: " ".join(t.split()[:40]) | |
| train_txt = {key40(json.loads(l)["text"]) for l in open(A + "/benchmark/training_groups.jsonl")} | |
| shared = {(r["query"], r["src_idx"]) for r in map(json.loads, open(A + "/benchmark/passages.jsonl")) if key40(r["text"]) in train_txt} | |
| touched = {g for g, l in lab.items() if any((g.split("::", 1)[1], s) in shared for s in l)} | |
| allp = {os.path.relpath(p, A + "/benchmark/predictions")[:-5]: R.per_group(lab, R.load_scorer(p)) | |
| for p in glob.glob(A + "/benchmark/predictions/**/*.json", recursive=True)} | |
| shift = {k: abs(np.mean(list(v.values())) - np.mean([x for g, x in v.items() if g not in touched])) for k, v in allp.items()} | |
| out["overlap"] = {"shared_passages": len(shared), "groups_touched": len([g for g in touched if g in rho["student4b_s42"]]), | |
| "max_abs_shift": round(float(max(shift.values())), 4), "argmax": max(shift, key=shift.get), | |
| "n_configurations": len(shift), | |
| "max_abs_shift_students": round(float(max(v for k, v in shift.items() if k.startswith("students/"))), 4), | |
| "signed_shift_student4b_s42": round(float(np.mean([x for g, x in allp["students/student_4b_s42"].items() if g not in touched]) | |
| - np.mean(list(allp["students/student_4b_s42"].values()))), 4)} | |
| json.dump(out, open(OUT, "w"), indent=1) | |
| print(out["per_query_mean"], out["top1_chance"], out["overlap"]) | |