File size: 4,647 Bytes
29671af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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)