Download aggregate_binary.py from azimi2kht/JEFFNet: direct link, hf CLI and curl.
- Browser
- Download file 14.4 kB
-
https://huggingface.co/azimi2kht/JEFFNet/resolve/main/aggregate_binary.py
- Command line
-
hf download hf://azimi2kht/JEFFNet/aggregate_binary.py
-
curl -L -o aggregate_binary.py https://huggingface.co/azimi2kht/JEFFNet/resolve/main/aggregate_binary.py
14.4 kB
| #!/usr/bin/env python3 | |
| import os | |
| import glob | |
| import csv | |
| import json | |
| import math | |
| import argparse | |
| from pathlib import Path | |
| import numpy as np | |
| from sklearn.metrics import roc_auc_score | |
| def safe_div(a: float, b: float) -> float: | |
| return float(a) / float(b) if b != 0 else float("nan") | |
| def binary_metrics_from_confusion(cm: np.ndarray, healthy_index: int): | |
| """ | |
| Collapse KxK confusion matrix into 2x2: | |
| Positive = Faulty = all classes except healthy_index | |
| Negative = Healthy = healthy_index | |
| Confusion matrix convention assumed: | |
| rows = true labels | |
| columns = predicted labels | |
| """ | |
| cm = np.asarray(cm, dtype=float) | |
| if cm.ndim != 2 or cm.shape[0] != cm.shape[1]: | |
| raise ValueError(f"Confusion matrix must be square, got {cm.shape}") | |
| k = cm.shape[0] | |
| if not (0 <= healthy_index < k): | |
| raise ValueError(f"healthy_index={healthy_index} out of range for K={k}") | |
| faulty_indices = [i for i in range(k) if i != healthy_index] | |
| TN = float(cm[healthy_index, healthy_index]) | |
| FP = float(cm[healthy_index, :].sum() - TN) # true healthy predicted as faulty | |
| FN = float(cm[:, healthy_index].sum() - TN) # true faulty predicted as healthy | |
| TP = float(cm[np.ix_(faulty_indices, faulty_indices)].sum()) | |
| total = TP + TN + FP + FN | |
| acc = safe_div(TP + TN, total) | |
| precision = safe_div(TP, TP + FP) | |
| recall = safe_div(TP, TP + FN) | |
| if precision + recall == 0: | |
| f1 = float("nan") | |
| else: | |
| f1 = safe_div(2 * precision * recall, precision + recall) | |
| denom = (TP + FP) * (TP + FN) * (TN + FP) * (TN + FN) | |
| if denom > 0: | |
| mcc = safe_div(TP * TN - FP * FN, math.sqrt(denom)) | |
| else: | |
| mcc = float("nan") | |
| return { | |
| "TP": TP, | |
| "TN": TN, | |
| "FP": FP, | |
| "FN": FN, | |
| "acc": acc, | |
| "precision": precision, | |
| "recall": recall, | |
| "f1": f1, | |
| "mcc": mcc, | |
| } | |
| def softmax(x: np.ndarray, axis: int = -1) -> np.ndarray: | |
| x = x - np.max(x, axis=axis, keepdims=True) | |
| ex = np.exp(x) | |
| return ex / np.sum(ex, axis=axis, keepdims=True) | |
| def try_load_logits_and_labels(run_dir: Path): | |
| """ | |
| Tries to load logits and labels from either run_dir or run_dir/test_metrics. | |
| AUC cannot be derived from confusion.npy alone. | |
| It requires per-sample labels and logits/probabilities. | |
| """ | |
| search_dirs = [ | |
| run_dir, | |
| run_dir / "test_metrics", | |
| ] | |
| logits = None | |
| labels = None | |
| for d in search_dirs: | |
| if not d.exists(): | |
| continue | |
| p_npy = d / "logits.npy" | |
| if logits is None and p_npy.exists(): | |
| arr = np.load(p_npy, allow_pickle=True) | |
| if isinstance(arr, np.ndarray) and arr.dtype == object and arr.shape == (): | |
| obj = arr.item() | |
| if isinstance(obj, dict): | |
| logits = obj.get("logits", obj.get("pred_logits", None)) | |
| labels = obj.get("labels", obj.get("y_true", obj.get("targets", None))) | |
| else: | |
| logits = arr | |
| p_npz = d / "logits.npz" | |
| if p_npz.exists(): | |
| z = np.load(p_npz, allow_pickle=True) | |
| if logits is None: | |
| for key in ["logits", "pred_logits", "probs", "probabilities"]: | |
| if key in z: | |
| logits = z[key] | |
| break | |
| if labels is None: | |
| for key in ["labels", "y_true", "targets"]: | |
| if key in z: | |
| labels = z[key] | |
| break | |
| if labels is None: | |
| for fname in ["labels.npy", "y_true.npy", "targets.npy", "target.npy"]: | |
| p = d / fname | |
| if p.exists(): | |
| labels = np.load(p, allow_pickle=True) | |
| break | |
| return logits, labels | |
| def auc_binary_faulty_vs_healthy(logits, labels, healthy_index: int): | |
| """ | |
| Binary AUC: | |
| y=1 -> faulty | |
| y=0 -> healthy | |
| Score: | |
| score_faulty = 1 - P(healthy) | |
| """ | |
| if logits is None or labels is None: | |
| return float("nan") | |
| logits = np.asarray(logits) | |
| labels = np.asarray(labels).reshape(-1) | |
| if logits.ndim != 2: | |
| return float("nan") | |
| if labels.shape[0] != logits.shape[0]: | |
| return float("nan") | |
| if not (0 <= healthy_index < logits.shape[1]): | |
| return float("nan") | |
| probs = softmax(logits, axis=1) | |
| score_faulty = 1.0 - probs[:, healthy_index] | |
| y_true_binary = (labels != healthy_index).astype(int) | |
| if len(np.unique(y_true_binary)) < 2: | |
| return float("nan") | |
| try: | |
| return float(roc_auc_score(y_true_binary, score_faulty)) | |
| except ValueError: | |
| return float("nan") | |
| def mean_std(values): | |
| values = np.asarray(values, dtype=float) | |
| valid = values[~np.isnan(values)] | |
| if len(valid) == 0: | |
| return float("nan"), float("nan") | |
| mean = float(np.mean(valid)) | |
| if len(valid) > 1: | |
| std = float(np.std(valid, ddof=1)) | |
| else: | |
| std = float("nan") | |
| return mean, std | |
| def find_run_dirs(root: Path): | |
| """ | |
| Supports both cases: | |
| Case A: | |
| root/ | |
| seed_1/ | |
| seed_2/ | |
| Case B: | |
| root/ | |
| fusion_xxx_1/ | |
| fusion_xxx_2/ | |
| Case C, your current training code likely: | |
| root is a prefix, and actual runs are siblings: | |
| root_1428/ | |
| root_1764/ | |
| root_4367/ | |
| """ | |
| root = root.resolve() | |
| candidates = [] | |
| if root.exists() and root.is_dir(): | |
| # Direct children with test_metrics/confusion.npy | |
| candidates.extend( | |
| p for p in root.iterdir() | |
| if p.is_dir() and (p / "test_metrics").exists() | |
| ) | |
| # Old style: root/seed_* | |
| candidates.extend( | |
| p for p in root.glob("seed_*") | |
| if p.is_dir() | |
| ) | |
| # If root itself is one run | |
| if (root / "test_metrics").exists(): | |
| candidates.append(root) | |
| # Prefix style: /path/name_1234 | |
| parent = root.parent | |
| prefix = root.name | |
| if parent.exists(): | |
| candidates.extend( | |
| p for p in parent.glob(prefix + "_*") | |
| if p.is_dir() and (p / "test_metrics").exists() | |
| ) | |
| # remove duplicates and sort | |
| unique = sorted(set(candidates), key=lambda p: str(p)) | |
| return unique | |
| def find_confusion_path(run_dir: Path): | |
| names = [ | |
| "confusion.npy", | |
| "confusion_matrix.npy", | |
| "cm.npy", | |
| ] | |
| for name in names: | |
| p = run_dir / "test_metrics" / name | |
| if p.exists(): | |
| return p | |
| for name in names: | |
| p = run_dir / name | |
| if p.exists(): | |
| return p | |
| return None | |
| def load_class_names_from_checkpoint(run_dir: Path): | |
| """ | |
| Reads class_names from best_model.pt if available. | |
| This does not load the model architecture. | |
| """ | |
| ckpt_path = run_dir / "best_model.pt" | |
| if not ckpt_path.exists(): | |
| return None | |
| try: | |
| import torch | |
| ckpt = torch.load(ckpt_path, map_location="cpu") | |
| return ckpt.get("class_names", None) | |
| except Exception: | |
| return None | |
| def resolve_healthy_index(run_dirs, healthy_index, healthy_class): | |
| if healthy_class is None: | |
| return healthy_index, None | |
| for rd in run_dirs: | |
| class_names = load_class_names_from_checkpoint(rd) | |
| if class_names is None: | |
| continue | |
| if healthy_class not in class_names: | |
| raise ValueError( | |
| f"healthy_class='{healthy_class}' was not found in class_names:\n" | |
| f"{class_names}" | |
| ) | |
| return int(class_names.index(healthy_class)), class_names | |
| raise ValueError( | |
| "Could not read class_names from best_model.pt. " | |
| "Use --healthy-index instead of --healthy-class." | |
| ) | |
| def maybe_percent(x, percent: bool): | |
| if isinstance(x, float) and not math.isnan(x): | |
| return 100.0 * x if percent else x | |
| return x | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| description="Compute derived binary healthy-vs-faulty metrics over 10 runs." | |
| ) | |
| parser.add_argument( | |
| "--root", | |
| type=str, | |
| required=True, | |
| help="Common output directory or common output prefix used during training.", | |
| ) | |
| parser.add_argument( | |
| "--healthy-index", | |
| type=int, | |
| default=None, | |
| help="Index of the healthy class. Use this if you know ImageFolder class order.", | |
| ) | |
| parser.add_argument( | |
| "--healthy-class", | |
| type=str, | |
| default=None, | |
| help="Name of the healthy class. Safer than index if best_model.pt contains class_names.", | |
| ) | |
| parser.add_argument( | |
| "--percent", | |
| action="store_true", | |
| help="Save/report metrics as percentages instead of fractions.", | |
| ) | |
| parser.add_argument( | |
| "--out-dir", | |
| type=str, | |
| default=None, | |
| help="Output directory. Default: root/avg_results if root is a directory, otherwise parent/root_name_avg_results.", | |
| ) | |
| parser.add_argument( | |
| "--out-csv", | |
| type=str, | |
| default="binary_metrics_per_run.csv", | |
| ) | |
| parser.add_argument( | |
| "--out-json", | |
| type=str, | |
| default="binary_metrics_summary.json", | |
| ) | |
| args = parser.parse_args() | |
| root = Path(args.root).resolve() | |
| run_dirs = find_run_dirs(root) | |
| if len(run_dirs) == 0: | |
| raise SystemExit(f"No run folders found for root/prefix: {root}") | |
| if args.healthy_index is None and args.healthy_class is None: | |
| raise SystemExit( | |
| "You must provide either --healthy-index or --healthy-class.\n" | |
| "For ISM, I recommend --healthy-class with the exact ImageFolder class folder name." | |
| ) | |
| healthy_index, class_names = resolve_healthy_index( | |
| run_dirs=run_dirs, | |
| healthy_index=args.healthy_index, | |
| healthy_class=args.healthy_class, | |
| ) | |
| if healthy_index is None: | |
| raise SystemExit("healthy_index could not be resolved.") | |
| if args.out_dir is not None: | |
| out_dir = Path(args.out_dir).resolve() | |
| else: | |
| if root.exists() and root.is_dir(): | |
| out_dir = root / "avg_results" | |
| else: | |
| out_dir = root.parent / f"{root.name}_avg_results" | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| per_run = [] | |
| for rd in run_dirs: | |
| cm_path = find_confusion_path(rd) | |
| if cm_path is None: | |
| print(f"[WARN] Missing confusion.npy for {rd}, skipping.") | |
| continue | |
| cm = np.load(cm_path, allow_pickle=True) | |
| metrics = binary_metrics_from_confusion(cm, healthy_index=healthy_index) | |
| logits, labels = try_load_logits_and_labels(rd) | |
| metrics["auc"] = auc_binary_faulty_vs_healthy( | |
| logits=logits, | |
| labels=labels, | |
| healthy_index=healthy_index, | |
| ) | |
| metrics["run_dir"] = rd.name | |
| metrics["confusion_path"] = str(cm_path) | |
| per_run.append(metrics) | |
| if len(per_run) == 0: | |
| raise SystemExit("No runs processed.") | |
| metric_keys = ["acc", "precision", "recall", "f1", "mcc", "auc"] | |
| summary = {} | |
| for key in metric_keys: | |
| values = [m[key] for m in per_run] | |
| mn, sd = mean_std(values) | |
| summary[key] = { | |
| "mean": maybe_percent(mn, args.percent), | |
| "std": maybe_percent(sd, args.percent), | |
| } | |
| csv_path = out_dir / args.out_csv | |
| json_path = out_dir / args.out_json | |
| header = ["run_dir", "TP", "TN", "FP", "FN"] + metric_keys + ["confusion_path"] | |
| with open(csv_path, "w", newline="", encoding="utf-8") as f: | |
| writer = csv.writer(f) | |
| writer.writerow(header) | |
| for m in per_run: | |
| row = [] | |
| for h in header: | |
| v = m.get(h, "") | |
| if h in metric_keys: | |
| v = maybe_percent(v, args.percent) | |
| if isinstance(v, float): | |
| if math.isnan(v): | |
| row.append("") | |
| else: | |
| row.append(f"{v:.6f}") | |
| else: | |
| row.append(v) | |
| writer.writerow(row) | |
| out = { | |
| "root_or_prefix": str(root), | |
| "num_processed_runs": len(per_run), | |
| "healthy_index": healthy_index, | |
| "healthy_class": args.healthy_class, | |
| "class_names": class_names, | |
| "metrics_are_percent": bool(args.percent), | |
| "positive_class": "faulty", | |
| "negative_class": "healthy", | |
| "summary_mean_std": summary, | |
| "per_run": per_run, | |
| "notes": [ | |
| "Binary metrics are derived by collapsing the multi-class confusion matrix into healthy vs faulty.", | |
| "Rows of the confusion matrix are assumed to be true labels; columns are assumed to be predicted labels.", | |
| "AUC requires per-sample logits/probabilities and labels. It cannot be recovered from confusion.npy alone.", | |
| ], | |
| } | |
| with open(json_path, "w", encoding="utf-8") as f: | |
| json.dump(out, f, indent=2) | |
| print("\nProcessed runs:") | |
| for m in per_run: | |
| auc_value = m["auc"] | |
| auc_str = "NA" if math.isnan(auc_value) else f"{maybe_percent(auc_value, args.percent):.4f}" | |
| print( | |
| f" {m['run_dir']}: " | |
| f"acc={maybe_percent(m['acc'], args.percent):.4f}, " | |
| f"pre={maybe_percent(m['precision'], args.percent):.4f}, " | |
| f"rec={maybe_percent(m['recall'], args.percent):.4f}, " | |
| f"f1={maybe_percent(m['f1'], args.percent):.4f}, " | |
| f"mcc={maybe_percent(m['mcc'], args.percent):.4f}, " | |
| f"auc={auc_str}" | |
| ) | |
| print("\nSummary: mean ± std") | |
| for key in metric_keys: | |
| mn = summary[key]["mean"] | |
| sd = summary[key]["std"] | |
| mn_s = "NA" if math.isnan(mn) else f"{mn:.6f}" | |
| sd_s = "NA" if math.isnan(sd) else f"{sd:.6f}" | |
| print(f" {key}: {mn_s} ± {sd_s}") | |
| print(f"\nSaved CSV: {csv_path}") | |
| print(f"Saved JSON: {json_path}") | |
| if any(math.isnan(m["auc"]) for m in per_run): | |
| print( | |
| "\n[NOTE] Some/all binary AUC values are NA because logits and labels were not found. " | |
| "AUC cannot be computed from confusion.npy alone." | |
| ) | |
| if __name__ == "__main__": | |
| main() |