|
| 1 | +"""Head-to-head evaluation: learned (frozen) vs rolling (online) detector. |
| 2 | +
|
| 3 | +Both detectors are run over the *same* labeled telemetry stream so their |
| 4 | +precision/recall are directly comparable. The stream is a warm-up block of clean |
| 5 | +data followed by a test block that interleaves normal samples with injected |
| 6 | +faults (thermal spikes, out-of-envelope yaw) at known positions. |
| 7 | +
|
| 8 | + python3 -m alerts.eval_detector |
| 9 | + python3 -m alerts.eval_detector --anomaly-rate 0.15 --test 3000 |
| 10 | +
|
| 11 | +This is the evidence behind the README's claim that the trained model beats the |
| 12 | +rolling fallback: the rolling detector adapts, but interspersed faults slowly |
| 13 | +leak into its moving baseline, costing recall. |
| 14 | +""" |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import argparse |
| 18 | +import json |
| 19 | + |
| 20 | +import numpy as np |
| 21 | + |
| 22 | +from alerts.anomaly import AnomalyDetector |
| 23 | +from alerts.detector import load_model, predict |
| 24 | +from alerts.train_detector import FEATURES, sample_anomalies, sample_normal |
| 25 | + |
| 26 | + |
| 27 | +def _scores(tp: int, fp: int, fn: int, n_norm: int) -> dict: |
| 28 | + precision = tp / (tp + fp) if (tp + fp) else 0.0 |
| 29 | + recall = tp / (tp + fn) if (tp + fn) else 0.0 |
| 30 | + f1 = 2 * precision * recall / (precision + recall) if (precision + recall) else 0.0 |
| 31 | + return {"precision": round(precision, 3), "recall": round(recall, 3), "f1": round(f1, 3), |
| 32 | + "false_positive_rate": round(fp / n_norm, 4) if n_norm else 0.0, |
| 33 | + "tp": tp, "fp": fp, "fn": fn} |
| 34 | + |
| 35 | + |
| 36 | +def build_stream(rng, n_test: int, anomaly_rate: float): |
| 37 | + """Return (vectors, labels) for the test block (1 = injected fault).""" |
| 38 | + labels = (rng.random(n_test) < anomaly_rate).astype(int) |
| 39 | + n_anom = int(labels.sum()) |
| 40 | + normals = sample_normal(n_test - n_anom, rng) |
| 41 | + anoms = sample_anomalies(max(1, n_anom), rng) |
| 42 | + vectors = np.zeros((n_test, len(FEATURES))) |
| 43 | + ni = ai = 0 |
| 44 | + for i, lab in enumerate(labels): |
| 45 | + if lab: |
| 46 | + vectors[i] = anoms[ai % len(anoms)] |
| 47 | + ai += 1 |
| 48 | + else: |
| 49 | + vectors[i] = normals[ni % len(normals)] |
| 50 | + ni += 1 |
| 51 | + return vectors, labels |
| 52 | + |
| 53 | + |
| 54 | +def eval_learned(model: dict, vectors: np.ndarray, labels: np.ndarray) -> dict: |
| 55 | + flags = np.array([predict(model, v) for v in vectors], dtype=int) |
| 56 | + tp = int(((flags == 1) & (labels == 1)).sum()) |
| 57 | + fp = int(((flags == 1) & (labels == 0)).sum()) |
| 58 | + fn = int(((flags == 0) & (labels == 1)).sum()) |
| 59 | + return _scores(tp, fp, fn, int((labels == 0).sum())) |
| 60 | + |
| 61 | + |
| 62 | +def eval_rolling(vectors: np.ndarray, labels: np.ndarray, warmup_block: np.ndarray) -> dict: |
| 63 | + det = AnomalyDetector(FEATURES, window=240, warmup=60, threshold=4.0, cooldown_s=0.0) |
| 64 | + now = 0.0 |
| 65 | + for v in warmup_block: # establish a clean baseline first |
| 66 | + for f, val in zip(FEATURES, v, strict=False): |
| 67 | + det.update("eval", f, float(val), now) |
| 68 | + now += 1.0 |
| 69 | + tp = fp = fn = 0 |
| 70 | + for v, lab in zip(vectors, labels, strict=False): |
| 71 | + hit = None |
| 72 | + for f, val in zip(FEATURES, v, strict=False): |
| 73 | + hit = det.update("eval", f, float(val), now) |
| 74 | + now += 1.0 |
| 75 | + flagged = hit is not None |
| 76 | + if flagged and lab: |
| 77 | + tp += 1 |
| 78 | + elif flagged and not lab: |
| 79 | + fp += 1 |
| 80 | + elif not flagged and lab: |
| 81 | + fn += 1 |
| 82 | + return _scores(tp, fp, fn, int((labels == 0).sum())) |
| 83 | + |
| 84 | + |
| 85 | +def main() -> None: |
| 86 | + ap = argparse.ArgumentParser(description="learned vs rolling anomaly detector") |
| 87 | + ap.add_argument("--model", default="alerts/model.json") |
| 88 | + ap.add_argument("--test", type=int, default=3000) |
| 89 | + ap.add_argument("--anomaly-rate", type=float, default=0.15) |
| 90 | + ap.add_argument("--seed", type=int, default=11) |
| 91 | + args = ap.parse_args() |
| 92 | + |
| 93 | + rng = np.random.default_rng(args.seed) |
| 94 | + warmup_block = sample_normal(400, rng) |
| 95 | + vectors, labels = build_stream(rng, args.test, args.anomaly_rate) |
| 96 | + model = load_model(args.model) |
| 97 | + |
| 98 | + result = { |
| 99 | + "test_samples": args.test, |
| 100 | + "injected_faults": int(labels.sum()), |
| 101 | + "learned": eval_learned(model, vectors, labels), |
| 102 | + "rolling": eval_rolling(vectors, labels, warmup_block), |
| 103 | + } |
| 104 | + print(json.dumps(result, indent=2)) |
| 105 | + |
| 106 | + |
| 107 | +if __name__ == "__main__": |
| 108 | + main() |
0 commit comments