Download scripts/build_benchmark.py from ranzouu/anomaly-detection-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 8.47 kB
-
https://huggingface.co/datasets/ranzouu/anomaly-detection-benchmark/resolve/main/scripts/build_benchmark.py
- Command line
-
hf download hf://datasets/ranzouu/anomaly-detection-benchmark/scripts/build_benchmark.py
-
curl -L -o build_benchmark.py https://huggingface.co/datasets/ranzouu/anomaly-detection-benchmark/resolve/main/scripts/build_benchmark.py
8.47 kB
| #!/usr/bin/env python3 | |
| """Gera um benchmark de detecção de anomalias com ground truth por construção. | |
| Protocolo: | |
| 1. sintetiza 180 dias de receita diária (tendência + sazonalidade semanal | |
| + ruído multiplicativo), tudo determinístico (seed fixa) | |
| 2. injeta 12 anomalias em datas conhecidas (6 spikes, 6 quedas, magnitudes | |
| variadas) — ground truth perfeito por construção | |
| 3. roda os detectores DO PRÓPRIO pacote (z-score, IQR, STL) sobre a série | |
| 4. exporta precision/recall/F1 por método, por tipo (spike/queda) e por | |
| magnitude — nada de lógica de detecção duplicada aqui | |
| Uso: python3 scripts/build_benchmark.py | |
| Saídas: data/benchmark_metrics.json, data/benchmark_expected.json, | |
| runs/benchmark_records.csv, runs/benchmark_summary.csv, | |
| runs/benchmark_by_type.csv, runs/benchmark_by_magnitude.csv | |
| """ | |
| from __future__ import annotations | |
| import csv | |
| import json | |
| from datetime import date, timedelta | |
| from pathlib import Path | |
| import numpy as np | |
| ROOT = Path(__file__).resolve().parents[1] | |
| DATA_DIR = ROOT / "data" | |
| RUNS_DIR = ROOT / "runs" | |
| SEED = 20260101 | |
| N_DAYS = 180 | |
| START = date(2025, 4, 1) | |
| BASE = 120_000.0 | |
| TREND_PER_DAY = 0.0004 | |
| NOISE_SIGMA = 0.025 | |
| # (dia_index, tipo, fator) — spike multiplica, queda divide; >= 15 e deixa folga no fim | |
| INJECTIONS = [ | |
| (30, "spike", 2.6), | |
| (52, "spike", 2.3), | |
| (88, "spike", 3.2), | |
| (120, "spike", 2.4), | |
| (150, "spike", 2.8), | |
| (168, "spike", 2.5), | |
| (41, "drop", 0.70), | |
| (66, "drop", 0.62), | |
| (100, "drop", 0.72), | |
| (135, "drop", 0.58), | |
| (158, "drop", 0.68), | |
| (175, "drop", 0.75), | |
| ] | |
| WEEKDAY_FACTOR = [1.02, 1.04, 1.03, 1.01, 0.99, 0.88, 0.86] # seg..dom | |
| def build_series() -> tuple[list[dict], dict[str, dict]]: | |
| rng = np.random.default_rng(SEED) | |
| points: list[dict] = [] | |
| injection_map: dict[str, dict] = {} | |
| for i in range(N_DAYS): | |
| day = START + timedelta(days=i) | |
| clean = BASE * (1 + TREND_PER_DAY * i) * WEEKDAY_FACTOR[day.weekday()] * float(rng.normal(1.0, NOISE_SIGMA)) | |
| value = clean | |
| for day_idx, kind, factor in INJECTIONS: | |
| if day_idx == i: | |
| value = clean * factor if kind == "spike" else clean * factor | |
| injection_map[day.isoformat()] = { | |
| "type": kind, | |
| "magnitude": factor if kind == "spike" else round(1 / factor, 2), | |
| "factor": factor, | |
| } | |
| points.append({"date": day.isoformat(), "metric": "revenue", "value": round(value, 2)}) | |
| # sanity: nenhuma inje colidindo | |
| assert len(injection_map) == len(INJECTIONS), "injeções colidiram em datas" | |
| return points, injection_map | |
| def band_of(meta: dict) -> str: | |
| """Balde de magnitude definido DENTRO do tipo: fator de spike 2.3 e fator | |
| de queda 0.70 não vivem na mesma escala.""" | |
| if meta["type"] == "spike": | |
| f = meta["factor"] | |
| return "spike >3.0x" if f > 3.0 else "spike 2.5-3.0x" if f >= 2.5 else "spike 2.0-2.5x" | |
| f = meta["factor"] | |
| return "queda >0.75" if f > 0.75 else "queda 0.65-0.75" if f >= 0.65 else "queda <0.65" | |
| def main() -> int: | |
| from leadforge_anomaly_detector.experiment import run_detection_paths | |
| points, injection_map = build_series() | |
| DATA_DIR.mkdir(parents=True, exist_ok=True) | |
| RUNS_DIR.mkdir(parents=True, exist_ok=True) | |
| metrics_path = DATA_DIR / "benchmark_metrics.json" | |
| expected_path = DATA_DIR / "benchmark_expected.json" | |
| with open(metrics_path, "w", encoding="utf-8") as f: | |
| json.dump(points, f, ensure_ascii=False, indent=2) | |
| expected_rows = [ | |
| {"date": d, "metric": "revenue", "is_anomaly": True, **meta} for d, meta in sorted(injection_map.items()) | |
| ] | |
| with open(expected_path, "w", encoding="utf-8") as f: | |
| json.dump(expected_rows, f, ensure_ascii=False, indent=2) | |
| records, summary = run_detection_paths(metrics_path, expected_path) | |
| # records: predições por método (is_anomaly = predito). Cruza com o ground truth. | |
| records_csv = ROOT / "runs" / "benchmark_records.csv" | |
| with open(records_csv, "w", newline="", encoding="utf-8") as f: | |
| writer = csv.DictWriter( | |
| f, fieldnames=["date", "metric", "value", "method", "score", "predicted", "expected", "expected_type", "expected_magnitude"] | |
| ) | |
| writer.writeheader() | |
| for r in records: | |
| meta = injection_map.get(r.date) | |
| writer.writerow( | |
| { | |
| "date": r.date, | |
| "metric": r.metric, | |
| "value": r.value, | |
| "method": r.method, | |
| "score": r.score, | |
| "predicted": int(bool(r.is_anomaly)), | |
| "expected": int(bool(meta)), | |
| "expected_type": meta["type"] if meta else "", | |
| "expected_magnitude": meta["magnitude"] if meta else "", | |
| } | |
| ) | |
| # agregações por método | |
| methods = sorted({r.method for r in records}) | |
| summary_rows, type_rows, magnitude_rows = [], [], [] | |
| for method in methods: | |
| preds = [r for r in records if r.method == method] | |
| expected_set = set(injection_map) | |
| tp = [r for r in preds if r.is_anomaly and r.date in expected_set] | |
| fp = [r for r in preds if r.is_anomaly and r.date not in expected_set] | |
| fn_dates = expected_set - {r.date for r in preds if r.is_anomaly} | |
| precision = len(tp) / (len(tp) + len(fp)) if (len(tp) + len(fp)) else 0.0 | |
| recall = len(tp) / (len(tp) + len(fn_dates)) if expected_set else 0.0 | |
| f1 = 2 * precision * recall / (precision + recall) if (precision + recall) else 0.0 | |
| summary_rows.append( | |
| { | |
| "method": method, | |
| "tp": len(tp), | |
| "fp": len(fp), | |
| "fn": len(fn_dates), | |
| "precision": round(precision, 4), | |
| "recall": round(recall, 4), | |
| "f1": round(f1, 4), | |
| } | |
| ) | |
| # por tipo | |
| for kind in ("spike", "drop"): | |
| expected_kind = {d for d, m in injection_map.items() if m["type"] == kind} | |
| tp_kind = [r for r in preds if r.is_anomaly and r.date in expected_kind] | |
| type_rows.append( | |
| { | |
| "method": method, | |
| "anomaly_type": kind, | |
| "detected": len(tp_kind), | |
| "total": len(expected_kind), | |
| "detection_rate": round(len(tp_kind) / len(expected_kind), 4), | |
| } | |
| ) | |
| # por tipo e magnitude (baldes definidos dentro de cada tipo) | |
| bands = sorted({band_of(m) for m in injection_map.values()}) | |
| for band_name in bands: | |
| expected_band = {d for d, m in injection_map.items() if band_of(m) == band_name} | |
| detected = [r for r in preds if r.is_anomaly and r.date in expected_band] | |
| magnitude_rows.append( | |
| { | |
| "method": method, | |
| "band": band_name, | |
| "detected": len(detected), | |
| "total": len(expected_band), | |
| "detection_rate": round(len(detected) / len(expected_band), 4), | |
| } | |
| ) | |
| def _dump(path: Path, rows: list[dict]) -> None: | |
| with open(path, "w", newline="", encoding="utf-8") as f: | |
| writer = csv.DictWriter(f, fieldnames=list(rows[0].keys())) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| _dump(RUNS_DIR / "benchmark_summary.csv", summary_rows) | |
| _dump(RUNS_DIR / "benchmark_by_type.csv", type_rows) | |
| _dump(RUNS_DIR / "benchmark_by_magnitude.csv", magnitude_rows) | |
| print(f"sintetizados: {len(points)} pontos | injetadas: {len(injection_map)} anomalias | seed={SEED}") | |
| print("=== resumo por método (precision/recall/F1):") | |
| for row in summary_rows: | |
| print(f" {row['method']:8s} P={row['precision']:.2f} R={row['recall']:.2f} F1={row['f1']:.2f} (tp={row['tp']} fp={row['fp']} fn={row['fn']})") | |
| print("=== por tipo (detection rate):") | |
| for row in type_rows: | |
| print(f" {row['method']:8s} {row['anomaly_type']:5s} {row['detected']}/{row['total']}") | |
| print("=== por banda de magnitude:") | |
| for row in magnitude_rows: | |
| print(f" {row['method']:8s} {row['band']:14s} {row['detected']}/{row['total']}") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |