Wendy-Fly commited on
Commit
2b769ad
·
verified ·
1 Parent(s): f4eceff

add script: write top-100 estimated position back to golden_set

Browse files
Files changed (1) hide show
  1. add_estimated_position.py +126 -0
add_estimated_position.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """把 top100 match 估出来的"均值 position" 写回 golden_set.csv。
3
+
4
+ 逻辑:
5
+ - 每条 golden 样本(共 1000 条)已经在 golden_top100.jsonl 里有 100 个最近邻 ruler item
6
+ - 对这 100 个邻居的 rank 求均值(也可以 sim-加权),作为 embedding 估出的 position
7
+ - 通过 task_id 把这个值合并回 csv,新列:estimated_position_top100
8
+ - 同时也保留几个有用的衍生字段:weighted_position / median_position / mean_score
9
+
10
+ 输出:
11
+ - golden_set_with_estimated.csv (默认;不覆盖原文件)
12
+
13
+ 用法:
14
+ python3 add_estimated_position.py
15
+ python3 add_estimated_position.py \
16
+ --csv /mnt/.../aipf_golden_set.csv \
17
+ --jsonl golden_top100.jsonl \
18
+ --output golden_set_with_estimated.csv
19
+ """
20
+ import argparse
21
+ import json
22
+ from pathlib import Path
23
+
24
+ import numpy as np
25
+ import pandas as pd
26
+
27
+
28
+ DEFAULTS = dict(
29
+ csv = "/mnt/bn/tns-algo-ue-my/biaowu/aipf_dm_metric/example/yss_ruler_eval/data/aipf_golden_set.csv",
30
+ jsonl = "golden_top100.jsonl",
31
+ output = "golden_set_with_estimated.csv",
32
+ id_col = "task_id",
33
+ )
34
+
35
+
36
+ def parse_args():
37
+ p = argparse.ArgumentParser()
38
+ p.add_argument("--csv", default=DEFAULTS["csv"])
39
+ p.add_argument("--jsonl", default=DEFAULTS["jsonl"])
40
+ p.add_argument("--output", default=DEFAULTS["output"])
41
+ p.add_argument("--id-col", default=DEFAULTS["id_col"])
42
+ return p.parse_args()
43
+
44
+
45
+ def main():
46
+ args = parse_args()
47
+
48
+ # 1) 读 jsonl,按 task_id 算各种聚合
49
+ print(f"[1] read jsonl: {args.jsonl}")
50
+ estimated = {}
51
+ with open(args.jsonl, "r", encoding="utf-8") as f:
52
+ for line in f:
53
+ line = line.strip()
54
+ if not line:
55
+ continue
56
+ r = json.loads(line)
57
+ ranks = np.array([t["rank"] for t in r["topk"]], dtype=float)
58
+ sims = np.array([t["sim"] for t in r["topk"]], dtype=float)
59
+ scores = np.array([t["score"] for t in r["topk"]], dtype=float)
60
+ wsim = sims.sum()
61
+
62
+ estimated[str(r["task_id"])] = {
63
+ "estimated_position_top100": float(ranks.mean()),
64
+ "estimated_position_top100_weighted": float((sims * ranks).sum() / max(wsim, 1e-12)),
65
+ "estimated_position_top100_median": float(np.median(ranks)),
66
+ "estimated_score_top100_mean": float(scores.mean()),
67
+ "estimated_score_top100_weighted": float((sims * scores).sum() / max(wsim, 1e-12)),
68
+ "top1_rank": int(ranks[0]),
69
+ "top1_sim": float(sims[0]),
70
+ }
71
+ print(f" -> {len(estimated)} rows in jsonl")
72
+
73
+ # 2) 读 csv
74
+ print(f"[2] read csv: {args.csv}")
75
+ df = pd.read_csv(args.csv, keep_default_na=False)
76
+ print(f" -> {len(df)} rows, {len(df.columns)} cols")
77
+ print(f" columns: {list(df.columns)}")
78
+
79
+ if args.id_col not in df.columns:
80
+ raise ValueError(f"id column '{args.id_col}' not in csv. available: {list(df.columns)}")
81
+
82
+ # 3) merge
83
+ print(f"[3] merge by {args.id_col}")
84
+ new_cols = [
85
+ "estimated_position_top100",
86
+ "estimated_position_top100_weighted",
87
+ "estimated_position_top100_median",
88
+ "estimated_score_top100_mean",
89
+ "estimated_score_top100_weighted",
90
+ "top1_rank",
91
+ "top1_sim",
92
+ ]
93
+ for col in new_cols:
94
+ df[col] = df[args.id_col].astype(str).map(lambda k: estimated.get(k, {}).get(col))
95
+
96
+ matched = df["estimated_position_top100"].notna().sum()
97
+ missing = len(df) - matched
98
+ print(f" matched: {matched}/{len(df)}")
99
+ if missing:
100
+ print(f" ⚠️ missing {missing} task_id(jsonl 里没有这些 id)")
101
+
102
+ # 4) 写出
103
+ print(f"[4] write: {args.output}")
104
+ df.to_csv(args.output, index=False)
105
+ print(f" done")
106
+
107
+ # 5) sanity: 看几行
108
+ print("\n[preview] 前 3 行新列:")
109
+ cols_show = [args.id_col, "label"] + new_cols
110
+ cols_show = [c for c in cols_show if c in df.columns]
111
+ print(df[cols_show].head(3).to_string(index=False))
112
+
113
+ # 6) 简单 stats
114
+ print("\n[stats] estimated_position_top100 分布:")
115
+ s = pd.to_numeric(df["estimated_position_top100"], errors="coerce")
116
+ print(f" min={s.min():.2f} max={s.max():.2f} mean={s.mean():.2f} median={s.median():.2f}")
117
+
118
+ if "label" in df.columns:
119
+ print("\n[stats] 按 label 分组:")
120
+ for lab, sub in df.groupby("label"):
121
+ ss = pd.to_numeric(sub["estimated_position_top100"], errors="coerce")
122
+ print(f" label={lab!r:>4} n={len(sub):>4} mean={ss.mean():.2f} median={ss.median():.2f}")
123
+
124
+
125
+ if __name__ == "__main__":
126
+ main()