kim1034's picture
v1.0: 3-fold split + multi-label GT masks
06eb8a6 verified
Raw History Blame Contribute Delete
8.35 kB
"""새 주제(부재 맥락) 용 3-fold 분할 + fold별 내부 검증 세트(inner_val) + 검증 보고서.
사용법:
python make_split3.py [--common ../common] [--data ../dacl10k_v2_devphase] [--workers N]
입력 (수정하지 않음): <common>/classes.json, <common>/gt_masks/<image>.npz (19,H,W bool),
<data>/annotations/{train,validation}/*.json (원래 split 확인용)
출력 (이 스크립트 폴더): classes.json(복사), split_3fold.json, split3_report.md, image_stats.json(사진별 집계 캐시)
- 층화 라벨: 사진마다 19개 클래스 포함 여부 (gt_masks 기준), iterstrat MultilabelStratifiedKFold(3, shuffle, seed 42)
- inner_val[k]: 시험 fold k 를 뺀 두 fold 사진 중 10%, 같은 19차원으로 iterstrat MultilabelStratifiedShuffleSplit(seed 42)
"""
import argparse
import glob
import json
import os
import shutil
from multiprocessing import Pool
import numpy as np
SEED = 42
N_FOLDS = 3
INNER = 0.10
FLAG_PP = 1.0
def image_stats(args):
path, ri, comp_idx = args
m = np.load(path)["mask"]
present = [bool(x.any()) for x in m]
anyc = m[comp_idx].any(0)
rust = m[ri]
return os.path.basename(path)[:-4], {"present": present, "npx": int(rust.size), "rust_px": int(rust.sum()),
"rust_on_comp": bool((rust & anyc).any())}
def main():
try:
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold, MultilabelStratifiedShuffleSplit
except ImportError:
raise SystemExit("iterstrat (iterative-stratification) 가 설치되어 있지 않습니다. 대체 방법을 쓰지 않고 중단합니다.")
here = os.path.dirname(os.path.abspath(__file__))
ap = argparse.ArgumentParser()
ap.add_argument("--common", default=os.path.join(here, "..", "common"))
ap.add_argument("--data", default=os.path.join(here, "..", "dacl10k_v2_devphase"))
ap.add_argument("--workers", type=int, default=6)
args = ap.parse_args()
common, data = os.path.abspath(args.common), os.path.abspath(args.data)
np.random.seed(SEED)
shutil.copyfile(os.path.join(common, "classes.json"), os.path.join(here, "classes.json"))
cl = json.load(open(os.path.join(here, "classes.json"), encoding="utf-8"))["classes"]
names_c = [c["name"] for c in cl]
comp_idx = [c["index"] for c in cl if c["type"] == "component"]
ri, wi = names_c.index("Rust"), names_c.index("Weathering")
orig = {}
for sp in ("train", "validation"):
for p in glob.glob(os.path.join(data, "annotations", sp, "*.json")):
orig[os.path.basename(p)[:-5]] = sp
names = sorted(orig)
assert len(names) == 7910, len(names)
cache = os.path.join(here, "image_stats.json")
if os.path.exists(cache):
st = json.load(open(cache, encoding="utf-8"))
else:
jobs = [(os.path.join(common, "gt_masks", n + ".npz"), ri, comp_idx) for n in names]
st = {}
with Pool(args.workers) as pool:
for i, (n, r) in enumerate(pool.imap_unordered(image_stats, jobs, chunksize=8)):
st[n] = r
if (i + 1) % 1000 == 0:
print(f"{i + 1}/{len(names)}", flush=True)
with open(cache, "w", encoding="utf-8") as f:
json.dump(st, f)
Y = np.array([st[n]["present"] for n in names], int)
X = np.zeros((len(names), 1))
fold = np.zeros(len(names), int)
for k, (_, te) in enumerate(MultilabelStratifiedKFold(n_splits=N_FOLDS, shuffle=True, random_state=SEED).split(X, Y)):
fold[te] = k
inner = {}
for k in range(N_FOLDS):
pool_idx = np.where(fold != k)[0]
msss = MultilabelStratifiedShuffleSplit(n_splits=1, test_size=INNER, random_state=SEED)
_, va = next(msss.split(X[pool_idx], Y[pool_idx]))
inner[str(k)] = sorted(names[i] for i in pool_idx[va])
with open(os.path.join(here, "split_3fold.json"), "w", encoding="utf-8") as f:
json.dump({"seed": SEED, "n_folds": N_FOLDS,
"stratify": "presence of 19 classes (14 damage + 5 component)", "grouping": "image",
"images": {n: {"fold": int(fold[i]), "orig_split": orig[n]} for i, n in enumerate(names)},
"inner_val": inner}, f, indent=1)
# ---- 보고서 ----
idx = {n: i for i, n in enumerate(names)}
F = range(N_FOLDS)
sel = {k: np.where(fold == k)[0] for k in F}
has_comp = Y[:, comp_idx].any(1)
rust_on = np.array([st[n]["rust_on_comp"] for n in names])
rust_px = np.array([st[n]["rust_px"] for n in names], float)
npx = np.array([st[n]["npx"] for n in names], float)
L = ["# 3-fold 분할 검증 보고서", "",
f"- 사진 {len(names)}장 (train {sum(v == 'train' for v in orig.values())}, validation "
f"{sum(v == 'validation' for v in orig.values())}), 교량 ID 없음 → 사진 단위 분할",
f"- 층화: 19개 클래스 포함 여부 (gt_masks 기준), iterstrat MultilabelStratifiedKFold(n_splits=3, shuffle=True, random_state={SEED})",
f"- inner_val: 시험 fold k 를 뺀 두 fold 의 {INNER:.0%}, 같은 19차원으로 MultilabelStratifiedShuffleSplit(random_state={SEED})",
f"- ⚠️ = fold 간 포함 비율 차이 > {FLAG_PP}%p", "",
"## fold별 요약", "", "| 항목 | " + " | ".join(f"fold {k}" for k in F) + " | 전체 |", "|---" * (N_FOLDS + 2) + "|"]
L.append("| 사진 | " + " | ".join(str(len(sel[k])) for k in F) + f" | {len(names)} |")
L.append("| 원래 train / validation | " + " | ".join(
f"{sum(orig[names[i]] == 'train' for i in sel[k])} / {sum(orig[names[i]] == 'validation' for i in sel[k])}" for k in F) + " | 6935 / 975 |")
warns = []
def row(label, mask, flag=True):
r = [mask[sel[k]].mean() * 100 for k in F]
spread = max(r) - min(r)
mark = " ⚠️" if flag and spread > FLAG_PP else ""
if mark:
warns.append(f"{label}: {spread:.2f}%p")
return f"| {label}{mark} | " + " | ".join(f"{int(mask[sel[k]].sum())} ({r[i]:.2f}%)" for i, k in enumerate(F)) \
+ f" | {int(mask.sum())} ({mask.mean() * 100:.2f}%) |"
L.append(row("부재 있는 사진", has_comp))
L.append(row("녹(Rust) 있는 사진", Y[:, ri].astype(bool)))
L.append(row("녹이 부재 위에 있는 사진", rust_on))
L.append(row("풍화(Weathering) 있는 사진", Y[:, wi].astype(bool)))
L.append("| 녹 픽셀 비율 | " + " | ".join(f"{rust_px[sel[k]].sum() / npx[sel[k]].sum() * 100:.3f}%" for k in F)
+ f" | {rust_px.sum() / npx.sum() * 100:.3f}% |")
L += ["", "## 클래스별 포함 사진 수 (비율)", "", "| index | 클래스 | 종류 | " + " | ".join(f"fold {k}" for k in F)
+ " | 전체 | fold 간 차이 (%p) |", "|---" * (N_FOLDS + 5) + "|"]
for c in cl:
j = c["index"]
r = [Y[sel[k], j].mean() * 100 for k in F]
spread = max(r) - min(r)
mark = " ⚠️" if spread > FLAG_PP else ""
if mark:
warns.append(f"{c['name']}: {spread:.2f}%p")
L.append(f"| {j} | {c['name']}{mark} | {'손상' if c['type'] == 'damage' else '부재'} | "
+ " | ".join(f"{int(Y[sel[k], j].sum())} ({r[i]:.2f}%)" for i, k in enumerate(F))
+ f" | {int(Y[:, j].sum())} ({Y[:, j].mean() * 100:.2f}%) | {spread:.2f} |")
L += ["", "## inner_val (fold k 학습 시 체크포인트 선택용)", "",
"| 시험 fold | 학습 풀 사진 | inner_val 사진 | 실제 학습 사진 | inner_val 녹 있는 사진 | inner_val 부재 있는 사진 |",
"|---|---:|---:|---:|---:|---:|"]
for k in F:
iv = np.array([idx[n] for n in inner[str(k)]])
pool_n = int((fold != k).sum())
assert all(fold[iv] != k)
L.append(f"| {k} | {pool_n} | {len(iv)} ({len(iv) / pool_n:.1%}) | {pool_n - len(iv)} | "
f"{int(Y[iv, ri].sum())} ({Y[iv, ri].mean():.1%}) | {int(has_comp[iv].sum())} ({has_comp[iv].mean():.1%}) |")
L += ["", "## 경고", ""] + ([f"- ⚠️ {w}" for w in warns] or [f"- 없음 (모든 항목의 fold 간 차이 ≤ {FLAG_PP}%p)"]) + [""]
with open(os.path.join(here, "split3_report.md"), "w", encoding="utf-8") as f:
f.write("\n".join(L))
print("warnings:", len(warns))
if __name__ == "__main__":
main()