File size: 7,853 Bytes
58a3849 | 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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | """Evaluation on the held-out TEST set (run once) + single-video prediction for the terminal.
Reports: top-1, macro-F1, per-class metrics, confusion matrix, confusable-pair recall,
calibration (ECE, before/after temperature scaling), accuracy-vs-coverage, latency, params/FLOPs.
"""
import argparse
import json
import logging
import os
import time
import numpy as np
import pandas as pd
import torch
from sklearn.metrics import classification_report, confusion_matrix, f1_score
from torch.utils.data import DataLoader
from airwriting_common import (CONFUSABLE, AirDataset, build_model, collect_logits, decide, ece,
fit_temperature, nll, preprocess, read_frames, softmax)
logging.getLogger("fvcore").setLevel(logging.ERROR)
def load_model(ckpt_path, device):
ck = torch.load(ckpt_path, map_location=device)
cfg = ck["config"]
model = build_model(len(cfg["classes"]), cfg["depth"], cfg["frames"], cfg["size"]).to(device)
model.load_state_dict(ck["model"])
return model.eval(), cfg
def pair_report(cm, names):
idx, rows = {n: i for i, n in enumerate(names)}, []
for a, b in CONFUSABLE:
ia, ib = idx[a], idx[b]
na, nb = cm[ia].sum(), cm[ib].sum()
if na == 0 or nb == 0:
continue
rows.append(dict(pair=f"{a}/{b}", recall_a=float(cm[ia, ia] / na), recall_b=float(cm[ib, ib] / nb),
a_as_b=float(cm[ia, ib] / na), b_as_a=float(cm[ib, ia] / nb),
pair_error=float((cm[ia, ib] + cm[ib, ia]) / (na + nb))))
return rows
def latency(model, ds, device, cfg, n=50):
x = torch.randn(1, 3, cfg["frames"], cfg["size"], cfg["size"], device=device)
sync = torch.cuda.synchronize if device.type == "cuda" else (lambda: None)
with torch.no_grad():
for _ in range(5):
model(x)
sync()
m = []
for _ in range(n):
t = time.perf_counter(); model(x); sync(); m.append((time.perf_counter() - t) * 1000)
e = []
for i in range(min(n, len(ds))):
t = time.perf_counter(); v, _ = ds[i]; model(v.unsqueeze(0).to(device)); sync()
e.append((time.perf_counter() - t) * 1000)
q = lambda v: dict(mean=float(np.mean(v)), p50=float(np.percentile(v, 50)), p95=float(np.percentile(v, 95)))
out = dict(model_only_ms=q(m), end_to_end_ms=q(e), params_millions=sum(p.numel() for p in model.parameters()) / 1e6)
try:
from fvcore.nn import FlopCountAnalysis
out["gflops"] = float(FlopCountAnalysis(model, x).total() / 1e9)
except Exception:
out["gflops"] = None
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--checkpoint", required=True)
ap.add_argument("--test-csv")
ap.add_argument("--val-csv", help="used ONLY to fit the calibration temperature")
ap.add_argument("--video-dir")
ap.add_argument("--out-dir", default="eval")
ap.add_argument("--batch-size", type=int, default=4)
ap.add_argument("--num-workers", type=int, default=4)
ap.add_argument("--latency-samples", type=int, default=50)
ap.add_argument("--max-samples", type=int, default=None)
ap.add_argument("--predict", help="path to ONE video: prints ACCEPT / RETRY / REJECT")
ap.add_argument("--conf-thr", type=float, default=0.80)
ap.add_argument("--margin", type=float, default=0.20)
a = ap.parse_args()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model, cfg = load_model(a.checkpoint, device)
names, sep = cfg["classes"], cfg["separate_contrast"]
if a.predict: # ---- terminal-style single prediction
x = preprocess(read_frames(a.predict, cfg["frames"], False), cfg["size"], False).unsqueeze(0)
with torch.no_grad():
p = softmax(model(x.to(device)).cpu().numpy())[0]
status, ch, conf = decide(p, names, a.conf_thr, a.margin)
print(json.dumps(dict(decision=status, character=ch, confidence=round(conf, 4))))
return
os.makedirs(a.out_dir, exist_ok=True)
kw = dict(num_workers=a.num_workers, pin_memory=device.type == "cuda")
te = AirDataset(a.test_csv, a.video_dir, cfg["frames"], cfg["size"], False, sep, "raise", a.max_samples)
logits, y = collect_logits(model, DataLoader(te, batch_size=a.batch_size, **kw), device, device.type == "cuda")
probs, pred = softmax(logits), logits.argmax(1)
present = sorted(set(y.tolist()))
res = dict(n_test=len(y), top1=float((pred == y).mean()),
macro_f1=float(f1_score(y, pred, labels=present, average="macro", zero_division=0)),
ece_raw=ece(probs, y), nll_raw=nll(probs, y))
if a.val_csv: # temperature is fitted on VAL, applied to TEST
va = AirDataset(a.val_csv, a.video_dir, cfg["frames"], cfg["size"], False, sep, "raise", a.max_samples)
vlog, vy = collect_logits(model, DataLoader(va, batch_size=a.batch_size, **kw), device, device.type == "cuda")
T = fit_temperature(vlog, vy)
pc = softmax(logits, T)
res.update(temperature=T, ece_calibrated=ece(pc, y), nll_calibrated=nll(pc, y))
probs = pc
cm = confusion_matrix(y, pred, labels=range(len(names)))
pd.DataFrame(cm, index=names, columns=names).to_csv(os.path.join(a.out_dir, "confusion_matrix.csv"))
rep = classification_report(y, pred, labels=present, target_names=[names[i] for i in present],
output_dict=True, zero_division=0)
pd.DataFrame(rep).T.to_csv(os.path.join(a.out_dir, "per_class.csv"))
pd.DataFrame(dict(filename=te.files, true=[names[i] for i in y], pred=[names[i] for i in pred],
confidence=probs.max(1))).to_csv(os.path.join(a.out_dir, "predictions.csv"), index=False)
res["confusable_pairs"] = pair_report(cm, names)
conf = probs.max(1) # accuracy vs coverage (abstention)
res["accuracy_vs_coverage"] = [dict(threshold=t, coverage=float((conf >= t).mean()),
accuracy_on_accepted=float((pred[conf >= t] == y[conf >= t]).mean())
if (conf >= t).any() else None)
for t in [0.5, 0.7, 0.8, 0.9, 0.95]]
res["terminal_rule"] = {}
dec = [decide(p, names, a.conf_thr, a.margin)[0] for p in probs]
acc_mask = np.array([d == "ACCEPT" for d in dec])
res["terminal_rule"] = dict(accept_rate=float(acc_mask.mean()),
error_when_accepted=float((pred[acc_mask] != y[acc_mask]).mean()) if acc_mask.any() else None)
res["latency"] = latency(model, te, device, cfg, a.latency_samples)
try:
import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt
norm = cm / np.maximum(cm.sum(1, keepdims=True), 1)
fig, ax = plt.subplots(figsize=(12, 10))
ax.imshow(norm, cmap="Blues"); ax.set_xticks(range(len(names))); ax.set_yticks(range(len(names)))
ax.set_xticklabels(names, rotation=90, fontsize=7); ax.set_yticklabels(names, fontsize=7)
ax.set_xlabel("predicted"); ax.set_ylabel("true"); ax.set_title("Confusion matrix (row-normalised)")
fig.savefig(os.path.join(a.out_dir, "confusion_matrix.png"), dpi=130, bbox_inches="tight")
except Exception as e:
print("plot skipped:", e)
json.dump(res, open(os.path.join(a.out_dir, "metrics.json"), "w"), indent=2)
print(json.dumps({k: v for k, v in res.items() if k not in ("confusable_pairs", "accuracy_vs_coverage")}, indent=2))
print("\nConfusable pairs:")
for r in res["confusable_pairs"]:
print({k: (round(v, 3) if isinstance(v, float) else v) for k, v in r.items()})
if __name__ == "__main__":
main()
|