File size: 14,373 Bytes
82eab55 | 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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 | #!/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() |