rockglacierNET / datapipeline /verify_dataset.py
kabiriitb's picture
Upload folder using huggingface_hub
820fab0 verified
Raw History Blame Contribute Delete
5.01 kB
"""
Step 4 — Verify the dataset before training.
Checks per split:
* feature/mask counts match and pair 1:1,
* every feature is (P,P,B), every mask is (P,P,1), feature/mask same H,W,
* no NaN/Inf in features, masks strictly 0/1,
* foreground actually exists.
"Is the mask region different?" — for glacier patches it compares the mean of a
few discriminative bands INSIDE vs OUTSIDE the mask; a clear difference proves
the mask marks a genuine landform, not random pixels. A few RGB+mask overlay
PNGs are saved to eyeball alignment.
"""
import os
import glob
import json
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def verify_dataset(cfg):
out = cfg["out_path"]
pdir = os.path.join(out, "patches")
P = cfg["patch_size"]
stats_path = os.path.join(pdir, "metadata", "norm_stats.json")
band_names = json.load(open(stats_path))["band_names"] if os.path.exists(stats_path) else []
B = len(band_names)
def bidx(name, d):
return band_names.index(name) if name in band_names else d
i_b2, i_b3, i_b4 = bidx("B2", 0), bidx("B3", 1), bidx("B4", 2)
probe = [(n, bidx(n, d)) for n, d in [("NDVI", 10), ("NDSI", 11), ("SLOPE", 27)]]
ov_dir = os.path.join(pdir, "metadata", "overlays")
os.makedirs(ov_dir, exist_ok=True)
lines = ["=" * 56, " DATASET VERIFICATION", "=" * 56]
ok = True
saved = 0
g_fg = g_px = 0
inside = {n: [] for n, _ in probe}
outside = {n: [] for n, _ in probe}
for split in ["train", "val", "test"]:
feats = sorted(glob.glob(os.path.join(pdir, split, "features", "*.npy")))
masks = sorted(glob.glob(os.path.join(pdir, split, "masks", "*.npy")))
lines.append(f"\n [{split}] features={len(feats)} masks={len(masks)}")
if {os.path.basename(f) for f in feats} != {os.path.basename(m) for m in masks}:
ok = False
lines.append(" !! feature/mask filenames do not pair 1:1")
n_bad = n_nan = n_badmask = n_fg = 0
s_fg = s_px = 0
for f in feats:
m = os.path.join(pdir, split, "masks", os.path.basename(f))
x, y = np.load(f), np.load(m)
if x.shape != (P, P, B) or y.shape != (P, P, 1) or x.shape[:2] != y.shape[:2]:
ok = False; n_bad += 1; continue
if not np.isfinite(x).all():
n_nan += 1
if not np.isin(np.unique(y), [0.0, 1.0]).all():
n_badmask += 1
fg = y[..., 0] > 0.5
s_fg += int(fg.sum()); s_px += y[..., 0].size
if fg.any():
n_fg += 1
bg = ~fg
for n, ix in probe:
inside[n].append(float(x[..., ix][fg].mean()))
if bg.any():
outside[n].append(float(x[..., ix][bg].mean()))
if saved < 12:
_overlay(x, fg, i_b4, i_b3, i_b2,
os.path.join(ov_dir, f"{split}_{os.path.basename(f)[:-4]}.png"))
saved += 1
if n_nan:
ok = False
lines += [f" bad shape : {n_bad}",
f" NaN/Inf feature : {n_nan}",
f" non-binary mask : {n_badmask}",
f" patches w/ glacier: {n_fg}/{len(feats)}"]
if s_px:
lines.append(f" foreground px : {100*s_fg/s_px:.3f}%")
g_fg += s_fg; g_px += s_px
if g_px:
lines.append(f"\n CLASS BALANCE: glacier={100*g_fg/g_px:.3f}% "
f"background={100*(g_px-g_fg)/g_px:.3f}%")
lines.append("\n MASK REGION DISTINCTNESS (mean inside vs outside mask)")
distinct = False
for n, _ in probe:
if inside[n] and outside[n]:
a, b = float(np.mean(inside[n])), float(np.mean(outside[n]))
lines.append(f" {n:6s}: inside={a:9.3f} outside={b:9.3f} diff={a-b:+9.3f}")
distinct |= abs(a - b) > 1e-3
lines.append(f" -> mask marks a distinct region: {'YES' if distinct else 'NO (suspicious!)'}")
ok &= distinct
lines.append(f"\n overlays: {saved} -> {os.path.relpath(ov_dir, out)}")
lines.append("\n RESULT: " + ("PASS ✅" if ok else "FAIL ❌ (see above)"))
report = "\n".join(lines)
print(report)
with open(os.path.join(pdir, "metadata", "verify_report.txt"), "w") as f:
f.write(report)
return ok
def _overlay(x, fg, ir, ig, ib, path):
rgb = np.stack([x[..., ir], x[..., ig], x[..., ib]], -1).astype("float32")
lo, hi = np.percentile(rgb, 2), np.percentile(rgb, 98)
rgb = np.clip((rgb - lo) / (hi - lo + 1e-6), 0, 1)
fig, ax = plt.subplots(1, 2, figsize=(7, 3.6))
ax[0].imshow(rgb); ax[0].set_title("RGB (B4,B3,B2)"); ax[0].axis("off")
ax[1].imshow(rgb)
ax[1].imshow(np.ma.masked_where(~fg, fg), cmap="autumn", alpha=0.5)
ax[1].set_title("mask overlay"); ax[1].axis("off")
plt.tight_layout(); plt.savefig(path, dpi=110); plt.close()