Datasets:
Tasks:
Object Detection
Formats:
imagefolder
Languages:
Japanese
Size:
1K - 10K
Tags:
yolo
ultralytics
document-layout-analysis
document-understanding
historical-documents
kuzushiji
License:
Download scripts/make_pid_split.py from nakamura196/ndl-layout-dataset: direct link, hf CLI and curl.
- Browser
- Download file 4.65 kB
-
https://huggingface.co/datasets/nakamura196/ndl-layout-dataset/resolve/main/scripts/make_pid_split.py
- Command line
-
hf download hf://datasets/nakamura196/ndl-layout-dataset/scripts/make_pid_split.py
-
curl -L -o make_pid_split.py https://huggingface.co/datasets/nakamura196/ndl-layout-dataset/resolve/main/scripts/make_pid_split.py
4.65 kB
| #!/usr/bin/env python3 | |
| """PID (資料) 単位の train/val/test 分割を作る。 | |
| Usage: | |
| python3 scripts/make_pid_split.py . # リポジトリのルートで実行する | |
| 既存の data/images/{train,val,test} は一切動かさない。PID が split をまたがない | |
| 新しい分割を、Ultralytics が読める画像パス一覧として書き出す: | |
| data/pid_train.txt / pid_val.txt / pid_test.txt | |
| data/data_pid.yaml | |
| data/pid_assignment.json | |
| 割り当ては固定 seed のランダム探索で決まる (再実行すると同じ結果になる)。 | |
| """ | |
| import random, re, json, sys | |
| from pathlib import Path | |
| from collections import defaultdict, Counter | |
| ROOT = Path(sys.argv[1] if len(sys.argv) > 1 else ".") | |
| TARGET = {"train": 0.70, "val": 0.20, "test": 0.10} | |
| NCLS = 5 | |
| TRIALS = 200000 | |
| SEED = 20260917 | |
| # ---- 読み込み ------------------------------------------------------------- | |
| # ラベル側を正本にする (画像と 1:1) | |
| imgs = sorted(p for s in ("train", "val", "test") | |
| for p in (ROOT / "data/labels" / s).glob("*.txt")) | |
| assert imgs, "ラベルが見つかりません" | |
| per_img_cls = {} # rel path -> Counter(cls -> boxes) | |
| groups = defaultdict(list) # pid -> [rel path] | |
| for p in imgs: | |
| rel = f"data/images/{p.parent.name}/{p.stem}.jpg" | |
| lab = p | |
| c = Counter() | |
| for line in lab.read_text().splitlines(): | |
| line = line.strip() | |
| if line: | |
| c[int(line.split()[0])] += 1 | |
| per_img_cls[rel] = c | |
| groups[p.stem.split("_")[0]].append(rel) | |
| pids = sorted(groups) | |
| n_img = len(imgs) | |
| tot_box = Counter() | |
| for c in per_img_cls.values(): | |
| tot_box.update(c) | |
| # ---- ランダム探索 --------------------------------------------------------- | |
| def cost(assign): | |
| """画像数と、クラス別矩形数の両方が 70/20/10 に近いほど小さい。""" | |
| n = Counter() | |
| box = defaultdict(Counter) | |
| for pid, sp in assign.items(): | |
| for rel in groups[pid]: | |
| n[sp] += 1 | |
| box[sp].update(per_img_cls[rel]) | |
| c = 0.0 | |
| for sp, t in TARGET.items(): | |
| c += abs(n[sp] / n_img - t) * 3.0 # 画像数の偏りを重く見る | |
| for k in range(NCLS): | |
| if tot_box[k]: | |
| c += abs(box[sp][k] / tot_box[k] - t) | |
| return c, n, box | |
| rnd = random.Random(SEED) | |
| best = None | |
| order = list(pids) | |
| for _ in range(TRIALS): | |
| rnd.shuffle(order) | |
| assign, filled = {}, Counter() | |
| for pid in order: | |
| # 目標に対していちばん足りていない split に入れる | |
| sp = min(TARGET, key=lambda s: filled[s] / n_img - TARGET[s]) | |
| assign[pid] = sp | |
| filled[sp] += len(groups[pid]) | |
| c = cost(assign) | |
| if best is None or c[0] < best[0][0]: | |
| best = (c, dict(assign)) | |
| (c, n, box), assign = best | |
| print(f"PID {len(pids)} / 画像 {n_img} cost={c:.4f}") | |
| for sp in ("train", "val", "test"): | |
| npid = sum(1 for v in assign.values() if v == sp) | |
| print(f" {sp:5s} PID {npid:3d} 画像 {n[sp]:4d} ({n[sp]/n_img*100:5.2f}%) " | |
| + " ".join(f"c{k}={box[sp][k]}" for k in range(NCLS))) | |
| # 検証: PID の重複が無いこと | |
| seen = defaultdict(set) | |
| for pid, sp in assign.items(): | |
| seen[sp].add(pid) | |
| assert not (seen["train"] & seen["val"]) and not (seen["train"] & seen["test"]) \ | |
| and not (seen["val"] & seen["test"]), "PID が split をまたいでいます" | |
| print("PID の重複: 0 件") | |
| # ---- 出力 ----------------------------------------------------------------- | |
| # Ultralytics は txt 内の "./" を txt 自身の親ディレクトリに置換するため、 | |
| # data/pid_*.txt に "./images/<元の split>/<file>.jpg" の形で書く。 | |
| out = ROOT / "data" | |
| for sp in ("train", "val", "test"): | |
| rels = sorted(r for pid, s in assign.items() if s == sp for r in groups[pid]) | |
| lines = [r.replace("data/", "./", 1) for r in rels] | |
| (out / f"pid_{sp}.txt").write_text("".join(l + "\n" for l in lines)) | |
| (out / "data_pid.yaml").write_text( | |
| "# PID (資料) 単位の分割。data.yaml の 70/20/10 はページ単位で、\n" | |
| "# 同じ資料が train と test の両方に入っている (資料単位のリーク)。\n" | |
| "# 汎化性能を測るときはこちらを使う。画像ファイルの場所は data.yaml と同じ。\n" | |
| "names:\n" + "".join(f"- {n}\n" for n in | |
| ["1_overall", "2_handwritten", "3_typography", "4_illustration", "5_stamp"]) | |
| + "nc: 5\n" | |
| + "train: pid_train.txt\nval: pid_val.txt\ntest: pid_test.txt\n") | |
| (out / "pid_assignment.json").write_text( | |
| json.dumps({pid: assign[pid] for pid in pids}, indent=1, ensure_ascii=False) + "\n") | |
| print("書き出し:", out) | |