Download evals/eval_classify.py from DeepLense/flowlensing: direct link, hf CLI and curl.
- Browser
- Download file 4.4 kB
-
https://huggingface.co/DeepLense/flowlensing/resolve/main/evals/eval_classify.py
- Command line
-
hf download hf://DeepLense/flowlensing/evals/eval_classify.py
-
curl -L -o eval_classify.py https://huggingface.co/DeepLense/flowlensing/resolve/main/evals/eval_classify.py
4.4 kB
| """3-class evaluation: can a classifier tell generated images apart correctly? | |
| WARNING: the preprocessing here is reconstructed, not recovered -- the original | |
| evaluation script did not run. On a short CPU smoke test this scored at chance, | |
| which may be too few ODE steps or may be wrong preprocessing; it could not be | |
| checked against real images because none survive. See README "Known gaps". | |
| Generates images for each dark matter class and reports accuracy, per-class | |
| AUC and the confusion matrix, using the ResNet trained on real images. | |
| python eval_classify.py --flow-ckpt X.pth --classifier-ckpt Y.pt --arch resnet34 | |
| """ | |
| import argparse, os, sys | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| from tqdm import tqdm | |
| from sklearn.metrics import (accuracy_score, roc_curve, auc, confusion_matrix, | |
| classification_report) | |
| from sklearn.preprocessing import label_binarize | |
| sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "code")) | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from common import (load_flow_model, load_classifier, sample_cfg, pick_device, | |
| to_imagenet_rgb, load_npy_image) | |
| CLASS_NAMES = ["axion", "cdm", "no_sub"] | |
| def classify(clf, imgs01, device): | |
| with torch.no_grad(): | |
| return F.softmax(clf(to_imagenet_rgb(imgs01.to(device))), dim=1).cpu().numpy() | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--flow-ckpt", help="generate samples with this model") | |
| ap.add_argument("--real-data", help="instead, classify real .npy under <dir>/<class>/") | |
| ap.add_argument("--classifier-ckpt", required=True) | |
| ap.add_argument("--arch", default="resnet34", choices=["resnet18", "resnet34"]) | |
| ap.add_argument("--n-per-class", type=int, default=400) | |
| ap.add_argument("--batch-size", type=int, default=50) | |
| ap.add_argument("--ode-steps", type=int, default=100) | |
| ap.add_argument("--cfg-scale", type=float, default=2.0) | |
| ap.add_argument("--device", default="auto") | |
| ap.add_argument("--seed", type=int, default=0) | |
| args = ap.parse_args() | |
| if not args.flow_ckpt and not args.real_data: | |
| raise SystemExit("pass --flow-ckpt (generated) or --real-data (real)") | |
| torch.manual_seed(args.seed) | |
| device = pick_device(args.device) | |
| print(f"device: {device}") | |
| clf = load_classifier(args.classifier_ckpt, args.arch, device) | |
| probs, labels = [], [] | |
| if args.flow_ckpt: | |
| flow = load_flow_model(args.flow_ckpt, "class", device) | |
| for cid, cname in enumerate(CLASS_NAMES): | |
| for i in tqdm(range(0, args.n_per_class, args.batch_size), desc=f"gen {cname}"): | |
| b = min(args.batch_size, args.n_per_class - i) | |
| cond = torch.full((b,), cid, dtype=torch.long) | |
| imgs = sample_cfg(flow, cond, args.ode_steps, args.cfg_scale, device) | |
| probs.append(classify(clf, imgs, device)) | |
| labels.extend([cid] * b) | |
| else: | |
| for cid, cname in enumerate(CLASS_NAMES): | |
| d = os.path.join(args.real_data, cname) | |
| files = sorted(f for f in os.listdir(d) if f.endswith(".npy"))[: args.n_per_class] | |
| for i in tqdm(range(0, len(files), args.batch_size), desc=f"real {cname}"): | |
| batch = torch.stack([load_npy_image(os.path.join(d, f)) | |
| for f in files[i : i + args.batch_size]]) | |
| probs.append(classify(clf, batch, device)) | |
| labels.extend([cid] * batch.shape[0]) | |
| probs = np.concatenate(probs) | |
| y = np.array(labels) | |
| pred = probs.argmax(1) | |
| print(f"\nAccuracy: {accuracy_score(y, pred):.4f}\n") | |
| print(classification_report(y, pred, target_names=CLASS_NAMES, digits=4)) | |
| yb = label_binarize(y, classes=[0, 1, 2]) | |
| print("Per-class AUC:") | |
| aucs = [] | |
| for i, name in enumerate(CLASS_NAMES): | |
| fpr, tpr, _ = roc_curve(yb[:, i], probs[:, i]) | |
| a = auc(fpr, tpr) | |
| aucs.append(a) | |
| print(f" {name:8s} {a:.4f}") | |
| print(f" {'macro':8s} {np.mean(aucs):.4f}") | |
| print("\nConfusion matrix (rows = true, cols = predicted):") | |
| print(" " + "".join(f"{c:>9s}" for c in CLASS_NAMES)) | |
| for name, row in zip(CLASS_NAMES, confusion_matrix(y, pred)): | |
| print(f" {name:8s} " + "".join(f"{v:9d}" for v in row)) | |
| if __name__ == "__main__": | |
| main() | |