Download MTLCC/code/eval_mtlcc.py from Dhruv1000/TSRDA: direct link, hf CLI and curl.
- Browser
- Download file 3.99 kB
-
https://huggingface.co/Dhruv1000/TSRDA/resolve/main/MTLCC/code/eval_mtlcc.py
- Command line
-
hf download hf://Dhruv1000/TSRDA/MTLCC/code/eval_mtlcc.py
-
curl -L -o eval_mtlcc.py https://huggingface.co/Dhruv1000/TSRDA/resolve/main/MTLCC/code/eval_mtlcc.py
3.99 kB
| """Evaluate a fine-tuned T-SRDA checkpoint on MTLCC eval.tileids (whole tiles). | |
| Reports (1) STCLN protocol - exactly test_STCLN.py: pixels with y_true>0 AND y_pred>0, | |
| confusion matrix over the classes present in y_true, nan-mean IoU/F1; | |
| (2) strict protocol - every pixel with y_true>0 (predicted background counts as an error). | |
| """ | |
| import argparse, json, time | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from torch.utils.data import DataLoader | |
| from sklearn.metrics import confusion_matrix, cohen_kappa_score | |
| import config as C | |
| from dataset import MTLCCTileDataset, test_patch_ids, val_patch_ids, pad_collate | |
| from model import UTAE_ASPP, UTAEClassificationDual | |
| def stcln_metrics(yt, yp): | |
| k = (yt > 0) & (yp > 0) | |
| yt, yp = yt[k], yp[k] | |
| labels = np.unique(yt) | |
| cm = confusion_matrix(yt, yp, labels=labels) | |
| tp = np.diag(cm).astype(float); fp = cm.sum(0) - tp; fn = cm.sum(1) - tp | |
| with np.errstate(divide="ignore", invalid="ignore"): | |
| iou = tp / (tp + fp + fn); rec = tp / (tp + fn); pre = tp / (tp + fp); f1 = 2 * rec * pre / (rec + pre) | |
| return dict(protocol="stcln", pixels=int(len(yt)), OA=float((yt == yp).mean()), | |
| mIoU=float(np.nanmean(iou)), mF1=float(np.nanmean(f1)), kappa=float(cohen_kappa_score(yt, yp)), | |
| per_class={int(c): dict(IoU=float(iou[i]), F1=float(f1[i]), UA=float(pre[i]), PA=float(rec[i])) | |
| for i, c in enumerate(labels)}) | |
| def strict_metrics(yt, yp): | |
| k = yt > 0 | |
| yt, yp = yt[k], yp[k] | |
| labels = list(range(1, C.N_CLASSES)) | |
| cm = confusion_matrix(yt, yp, labels=labels) | |
| tp = np.diag(cm).astype(float); fp = cm.sum(0) - tp; fn = cm.sum(1) - tp | |
| present = cm.sum(1) > 0 | |
| with np.errstate(divide="ignore", invalid="ignore"): | |
| iou = tp / (tp + fp + fn); f1 = 2 * tp / (2 * tp + fp + fn) | |
| return dict(protocol="strict", pixels=int(len(yt)), OA=float((yt == yp).mean()), | |
| mIoU=float(np.nanmean(iou[present])), mF1=float(np.nanmean(f1[present])), kappa=float(cohen_kappa_score(yt, yp))) | |
| def load_network(ckpt, device): | |
| enc = UTAE_ASPP(n_channels=C.N_CHANNELS, d_model=C.D_MODEL, n_heads=C.N_HEADS) | |
| net = UTAEClassificationDual(enc, d_model=C.D_MODEL, num_classes=C.N_CLASSES) | |
| sd = torch.load(ckpt, map_location="cpu", weights_only=False)["model_state_dict"] | |
| net.load_state_dict(sd, strict=True) | |
| return net.to(device).eval() | |
| def predict_split(net, ids, device, batch): | |
| dl = DataLoader(MTLCCTileDataset(ids, train=False), batch_size=batch, shuffle=False, num_workers=8, collate_fn=pad_collate) | |
| yts, yps = [], [] | |
| for bi, ((x, pos, _), y) in enumerate(dl): | |
| with torch.autocast("cuda", dtype=torch.float16): | |
| out = net(x.to(device), pos.to(device)) | |
| yps.append(out["refined_logits"].float().argmax(1).cpu().numpy().ravel()); yts.append(y.numpy().ravel()) | |
| if bi % 50 == 0: print(f" batch {bi}/{len(dl)}", flush=True) | |
| return np.concatenate(yts), np.concatenate(yps) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--ckpt", required=True); ap.add_argument("--split", choices=["test", "val"], default="test") | |
| ap.add_argument("--out", default=""); a = ap.parse_args() | |
| torch.manual_seed(C.SEED); dev = torch.device("cuda") | |
| net = load_network(a.ckpt, dev) | |
| ids = test_patch_ids() if a.split == "test" else val_patch_ids() | |
| t0 = time.time(); yt, yp = predict_split(net, ids, dev, C.EVAL_BATCH) | |
| res = dict(ckpt=a.ckpt, split=a.split, tiles=len(ids), seconds=time.time() - t0, | |
| stcln=stcln_metrics(yt, yp), strict=strict_metrics(yt, yp)) | |
| for k in ("stcln", "strict"): | |
| r = res[k]; print(f"[{a.split} {k}] OA={r['OA']:.4f} mIoU={r['mIoU']:.4f} mF1={r['mF1']:.4f} kappa={r['kappa']:.4f} px={r['pixels']}") | |
| out = Path(a.out or (Path(a.ckpt).parent / f"eval_{a.split}.json")); out.write_text(json.dumps(res, indent=1)); print("saved", out) | |
| if __name__ == "__main__": | |
| main() | |