| |
| """ |
| 按 JSON 每条记录里的 "task" 字段划分 train / test,保证同一 task 只出现在一侧(无 overlap)。 |
| 先在「唯一 task」集合上做 8:2 划分,再把属于各 task 的样本归入对应集合。 |
| |
| 用法: |
| python split_metadata_by_task.py \\ |
| --input train_metadata_100.json \\ |
| --out_train train_metadata_100_train.json \\ |
| --out_test train_metadata_100_test.json \\ |
| --ratio_train 0.8 \\ |
| --seed 42 |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import random |
| from collections import Counter |
|
|
|
|
| def main(): |
| p = argparse.ArgumentParser(description="Split metadata JSON by task (no task overlap between splits).") |
| p.add_argument("--input", "-i", type=str, default="train_metadata_100.json") |
| p.add_argument("--out_train", type=str, default="train_metadata_100_train.json") |
| p.add_argument("--out_test", type=str, default="train_metadata_100_test.json") |
| p.add_argument("--ratio_train", type=float, default=0.8, help="Fraction of unique tasks assigned to train (default 0.8).") |
| p.add_argument("--seed", type=int, default=42, help="Shuffle seed for reproducible task split.") |
| args = p.parse_args() |
|
|
| if not 0.0 < args.ratio_train < 1.0: |
| raise ValueError("ratio_train must be in (0, 1).") |
|
|
| with open(args.input, "r", encoding="utf-8") as f: |
| records = json.load(f) |
| if not isinstance(records, list): |
| raise ValueError("Top-level JSON must be a list of objects.") |
|
|
| for i, r in enumerate(records): |
| if "task" not in r: |
| raise KeyError(f"Record {i} missing 'task' field.") |
|
|
| unique_tasks = sorted({r["task"] for r in records}) |
| n_tasks = len(unique_tasks) |
|
|
| rng = random.Random(args.seed) |
| shuffled = list(unique_tasks) |
| rng.shuffle(shuffled) |
|
|
| if n_tasks < 2: |
| print("Warning: only one unique task; all records -> train, test is empty.") |
| train_tasks = set(shuffled) |
| test_tasks = set() |
| else: |
| |
| n_train_tasks = int(n_tasks * args.ratio_train) |
| n_train_tasks = max(1, min(n_tasks - 1, n_train_tasks)) |
| train_tasks = set(shuffled[:n_train_tasks]) |
| test_tasks = set(shuffled[n_train_tasks:]) |
|
|
| train_records = [r for r in records if r["task"] in train_tasks] |
| test_records = [r for r in records if r["task"] in test_tasks] |
|
|
| overlap = train_tasks & test_tasks |
| if overlap: |
| raise RuntimeError(f"Internal error: overlapping tasks {overlap}") |
|
|
| |
| missing = [r["task"] for r in records if r["task"] not in train_tasks and r["task"] not in test_tasks] |
| if missing: |
| raise RuntimeError(f"Some tasks not in split: {set(missing)}") |
|
|
| with open(args.out_train, "w", encoding="utf-8") as f: |
| json.dump(train_records, f, indent=4, ensure_ascii=False) |
| with open(args.out_test, "w", encoding="utf-8") as f: |
| json.dump(test_records, f, indent=4, ensure_ascii=False) |
|
|
| ct_train = Counter(r["task"] for r in train_records) |
| ct_test = Counter(r["task"] for r in test_records) |
|
|
| print(f"Input: {args.input}") |
| print(f" total records: {len(records)}") |
| print(f" unique tasks: {n_tasks}") |
| print(f"Split (by task): train_tasks={len(train_tasks)}, test_tasks={len(test_tasks)} (ratio ~ {args.ratio_train:.1f} : {1-args.ratio_train:.1f})") |
| print(f" train records: {len(train_records)}") |
| print(f" test records: {len(test_records)}") |
| print(f" seed: {args.seed}") |
| print(f"Wrote: {args.out_train}") |
| print(f"Wrote: {args.out_test}") |
|
|
| |
| train_task_keys = set(ct_train.keys()) |
| test_task_keys = set(ct_test.keys()) |
| assert not (train_task_keys & test_task_keys), "task overlap between train and test samples" |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|