149 lines
5.1 KiB
Markdown
149 lines
5.1 KiB
Markdown
---
|
|
id: wiki-2026-0508-anomaly-detection
|
|
title: Anomaly Detection
|
|
category: 10_Wiki/Topics
|
|
status: verified
|
|
canonical_id: self
|
|
aliases: [Outlier Detection, Novelty Detection, 이상 탐지]
|
|
duplicate_of: none
|
|
source_trust_level: A
|
|
confidence_score: 0.9
|
|
verification_status: applied
|
|
tags: [security, ml, monitoring, observability]
|
|
raw_sources: []
|
|
last_reinforced: 2026-05-10
|
|
github_commit: applied
|
|
tech_stack:
|
|
language: Python
|
|
framework: scikit-learn/PyOD/Prometheus
|
|
---
|
|
|
|
# Anomaly Detection
|
|
|
|
## 매 한 줄
|
|
> **"매 normal 의 boundary 를 학습하고 그 밖을 flag 한다."**. Anomaly detection 은 fraud, intrusion, equipment failure, log spike 등을 unsupervised 로 발견하는 매 core observability/security primitive. 2026 의 standard 는 Isolation Forest + LSTM-AE + transformer-based time-series (PatchTST, TimesNet).
|
|
|
|
## 매 핵심
|
|
|
|
### 매 Anomaly Type 3가지
|
|
- **Point anomaly**: 매 single observation 이 outlier — credit card 단일 거래.
|
|
- **Contextual anomaly**: 매 context 에서만 anomaly — 여름의 영하 온도.
|
|
- **Collective anomaly**: 매 group 으로만 anomaly — DDoS 의 packet sequence.
|
|
|
|
### 매 Algorithm Family
|
|
- **Statistical**: z-score, MAD, Grubbs, EWMA — 매 univariate baseline.
|
|
- **Distance-based**: kNN, LOF — 매 density 차이로 detect.
|
|
- **Tree-based**: Isolation Forest, Extended IF — 매 high-dim 잘 작동.
|
|
- **Reconstruction**: Autoencoder, VAE — 매 reconstruction error = anomaly score.
|
|
- **Time-series DL**: LSTM-AE, Transformer (PatchTST 2024, TimesNet) — 매 SOTA 2026.
|
|
- **One-class**: One-Class SVM, Deep SVDD — 매 normal-only training.
|
|
|
|
### 매 응용
|
|
1. **Fraud detection**: payment, account takeover.
|
|
2. **Intrusion detection (IDS)**: network traffic anomaly.
|
|
3. **Predictive maintenance**: vibration sensor, temp.
|
|
4. **APM**: latency/error rate spike — Datadog Watchdog, New Relic.
|
|
5. **Log anomaly**: unseen log template — DeepLog, LogBERT.
|
|
|
|
## 💻 패턴
|
|
|
|
### Isolation Forest baseline
|
|
```python
|
|
from sklearn.ensemble import IsolationForest
|
|
import numpy as np
|
|
|
|
# 매 contamination = expected anomaly fraction
|
|
clf = IsolationForest(contamination=0.01, n_estimators=200, random_state=42)
|
|
clf.fit(X_train)
|
|
scores = -clf.score_samples(X_test) # 매 high score = more anomalous
|
|
preds = clf.predict(X_test) # -1=anomaly, 1=normal
|
|
```
|
|
|
|
### LOF for density anomaly
|
|
```python
|
|
from sklearn.neighbors import LocalOutlierFactor
|
|
lof = LocalOutlierFactor(n_neighbors=20, contamination=0.01, novelty=True)
|
|
lof.fit(X_train)
|
|
anomaly_score = -lof.score_samples(X_test)
|
|
```
|
|
|
|
### Autoencoder reconstruction error (PyTorch)
|
|
```python
|
|
import torch.nn as nn
|
|
class AE(nn.Module):
|
|
def __init__(self, d=64):
|
|
super().__init__()
|
|
self.enc = nn.Sequential(nn.Linear(d,32), nn.ReLU(), nn.Linear(32,8))
|
|
self.dec = nn.Sequential(nn.Linear(8,32), nn.ReLU(), nn.Linear(32,d))
|
|
def forward(self, x): return self.dec(self.enc(x))
|
|
|
|
# 매 train on normal only — anomaly = high reconstruction error
|
|
recon = model(x)
|
|
score = ((x - recon) ** 2).mean(dim=1)
|
|
```
|
|
|
|
### EWMA streaming detector
|
|
```python
|
|
class EWMA:
|
|
def __init__(self, alpha=0.1, k=3.0):
|
|
self.alpha, self.k = alpha, k
|
|
self.mu = self.var = None
|
|
def step(self, x):
|
|
if self.mu is None: self.mu, self.var = x, 1.0; return False
|
|
z = abs(x - self.mu) / (self.var ** 0.5 + 1e-9)
|
|
self.mu = self.alpha * x + (1 - self.alpha) * self.mu
|
|
self.var = self.alpha * (x - self.mu)**2 + (1 - self.alpha) * self.var
|
|
return z > self.k
|
|
```
|
|
|
|
### PyOD ensemble
|
|
```python
|
|
from pyod.models.iforest import IForest
|
|
from pyod.models.lof import LOF
|
|
from pyod.models.combination import average
|
|
|
|
scores = np.column_stack([
|
|
IForest().fit(X).decision_function(X),
|
|
LOF().fit(X).decision_function(X),
|
|
])
|
|
ensemble_score = average(scores)
|
|
```
|
|
|
|
## 매 결정 기준
|
|
| 상황 | Algorithm |
|
|
|---|---|
|
|
| Tabular, low-dim | Isolation Forest |
|
|
| Tabular, density 중요 | LOF |
|
|
| Time-series univariate | EWMA / Prophet |
|
|
| Time-series multivariate | LSTM-AE / PatchTST |
|
|
| Image | PaDiM / PatchCore |
|
|
| Log sequence | LogBERT / DeepLog |
|
|
|
|
**기본값**: 매 Isolation Forest baseline → 부족시 deep model.
|
|
|
|
## 🔗 Graph
|
|
- 부모: [[Statistics & Data Analysis]]
|
|
- 변형: [[Inferential-Statistics]]
|
|
- 응용: [[Malware-Analysis]] · [[Deepfake-Detection]] · [[Logging_and_Error_Handling]]
|
|
- Adjacent: [[경고 피로 (Alert Fatigue)]]
|
|
|
|
## 🤖 LLM 활용
|
|
**언제**: log template 추출, anomaly explanation generation, false-positive triage.
|
|
**언제 X**: 매 high-frequency stream 의 inner-loop scoring (use specialized model).
|
|
|
|
## ❌ 안티패턴
|
|
- **Threshold hard-coding**: 매 environment drift 시 무용지물 — adaptive threshold 사용.
|
|
- **Class imbalance 무시**: 매 anomaly 0.1% 일 때 accuracy 99.9% 무의미 — PR-AUC.
|
|
- **Train on contaminated data**: 매 anomaly 가 train set 에 섞이면 mask 됨.
|
|
- **Alert fatigue**: 매 raw score 그대로 alert 면 dev 가 무시.
|
|
|
|
## 🧪 검증 / 중복
|
|
- Verified: Liu et al. 2008 (Isolation Forest); PyOD docs; Nie et al. 2023 (PatchTST).
|
|
- 신뢰도 A.
|
|
|
|
## 🕓 Changelog
|
|
| 날짜 | 변경 |
|
|
|---|---|
|
|
| 2026-05-08 | Phase 1 |
|
|
| 2026-05-10 | Manual cleanup — algorithm taxonomy + PyOD/AE patterns |
|