File size: 4,445 Bytes
53e0dae |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
import os
import json
import argparse
from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt
# ------------------ 参数解析 ------------------ #
def parse_args():
p = argparse.ArgumentParser()
p.add_argument("root", type=str,
help="Directory containing 12 month subfolders (e.g., 2407 .. 2506)")
p.add_argument("--out-dir", type=str, default=None,
help="Output directory (default: ROOT)")
return p.parse_args()
# ------------------ JSON加载函数 ------------------ #
def load_month_values_json(root: Path, month: str):
# 常见路径候选
candidates = []
candidates.append(root / month / "values.json")
candidates.append(root / f"{month}_full" / "values.json")
candidates.append(root / f"{month}_lr4e-5" / "values.json")
# fallback:任意以 month 开头的子目录
for path in sorted(root.glob(f"{month}*/values.json")):
if path not in candidates:
candidates.append(path)
for path in sorted(root.glob(f"{month}*/metrics.json")):
if path not in candidates:
candidates.append(path)
for c in candidates:
if c.exists():
return c
return None
# ------------------ 主逻辑 ------------------ #
def main():
args = parse_args()
root = Path(args.root)
out_dir = Path(args.out_dir) if args.out_dir else root
months = ["origin", "2407","2408","2409","2410","2411","2412",
"2501","2502","2503","2504","2505","2506"]
main_tasks = [
"arc_easy",
"arc_challenge",
"hellaswag",
"sciq",
"truthfulqa_mc1",
"truthfulqa_mc2",
]
records = []
for tag in months:
path = load_month_values_json(root, tag)
if path is None:
continue
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
for rec in data.get("tasks", []):
task = rec.get("task", "")
metric = rec.get("metric", "")
value = rec.get("value", None)
if task in main_tasks and metric in ("acc", "acc_norm"):
records.append({
"month": tag,
"task": task,
"metric": metric,
"value": value
})
for rec in data.get("groups", []):
group = rec.get("group", "")
metric = rec.get("metric", "")
value = rec.get("value", None)
if group == "mmlu" and metric == "acc":
records.append({
"month": tag,
"task": "mmlu",
"metric": "acc",
"value": value
})
df = pd.DataFrame.from_records(records)
if df.empty:
df = pd.DataFrame(columns=["month","task","metric","value"])
# 月份排序
def month_sort_key(x):
if x == "origin":
return (0, 0)
try:
return (1, int(x))
except Exception:
return (2, x)
df["month"] = pd.Categorical(
df["month"],
categories=sorted(df["month"].unique(), key=month_sort_key),
ordered=True
)
df = df.sort_values(["task","metric","month"])
# 保存 CSV
csv_path = out_dir / "monthly_metrics.csv"
df.to_csv(csv_path, index=False)
# 画折线图
plt.figure(figsize=(12, 6))
series_keys = sorted(df[["task","metric"]].drop_duplicates().apply(tuple, axis=1))
n = len(series_keys)
cmap = plt.colormaps['tab20'].resampled(n)
for i, (task, metric) in enumerate(series_keys):
sub = df[(df["task"] == task) & (df["metric"] == metric)].sort_values("month")
if sub.empty:
continue
color = cmap(i % n) if n <= 20 else cmap(i / n)
plt.plot(sub["month"].astype(str), sub["value"],
marker="o",
color=color,
label=f"{task}—{metric}")
plt.xlabel("Month")
plt.ylabel("Score")
plt.title("Monthly Evaluation Trends (Main Tasks)")
plt.legend(loc='best', bbox_to_anchor=(1, 0.5))
plt.tight_layout()
png_path = out_dir / "monthly_metrics.png"
plt.savefig(png_path, dpi=150)
if __name__ == "__main__":
main()
|