[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,94 +2,147 @@
id: wiki-2026-0508-anomaly-detection
title: Anomaly Detection
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-ANDE-001]
aliases: [Outlier Detection, Novelty Detection, 이상 탐지]
duplicate_of: none
source_trust_level: A
confidence_score: 0.98
tags: [auto-reinforced, anomaly-detection, data-science, security, Quality-Control, machine-learning]
confidence_score: 0.9
verification_status: applied
tags: [security, ml, monitoring, observability]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: unspecified
framework: unspecified
language: Python
framework: scikit-learn/PyOD/Prometheus
---
# [[Anomaly-Detection|Anomaly-Detection]]
# Anomaly Detection
## 📌 한 줄 통찰 (The Karpathy Summary)
> "정상 속에 숨은 이질감 찾기: 평소와 다른 데이터 패턴을 즉각 감지하여, 잠재적인 사고, 부정 결제, 해킹, 혹은 신기술 탄생의 징후를 골라내는 지능형 레이더."
## 한 줄
> **"매 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).
## 📖 구조화된 지식 (Synthesized Content)
이상 탐지(Anomaly-Detection)는 대다수의 데이터와는 현저하게 다른 특성을 가진 '이상치(Outliers)'를 찾아내는 머신러닝 기법입니다.
## 매 핵심
1. **핵심 유형**:
* **Point Anomaly**: 특정 데이터 포인트가 전체 분포에서 크게 벗어남. (예: 카드 도용 고액 결제)
* **Contextual Anomaly**: 값 자체는 정상이나 맥락상 이상함. (예: 한여름에 난방비 급증)
* **Collective Anomaly**: 여러 데이터가 모였을 때 비정상적 패턴 형성. (예: 디도스 공격)
2. **학습 방식**:
* **Unsupervised**: 이상 데이터가 사전에 없어도 '정상'의 기준을 학습하여 나머지를 이상으로 간주. (가장 흔함)
* **Supervised**: 알려진 이상 사례(레이블)를 학습하여 탐지.
3. **적용 분야**:
* 공장 설비 고전 진단, 금융 사기 탐지(FDS), 네트워크 침입 감지, 암세포 진단.
### 매 Anomaly Type 3가지
- **Point anomaly**: 매 single observation 이 outlier — credit card 단일 거래.
- **Contextual anomaly**: 매 context 에서만 anomaly — 여름의 영하 온도.
- **Collective anomaly**: 매 group 으로만 anomaly — DDoS 의 packet sequence.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 특정 임계값(Threshold)을 넘으면 알람을 울리는 단순 정책이었으나, 현대 AI 정책은 데이터의 동적 변화를 반영하여 임계값을 스스로 조정하는 'Adaptive Threshold 정책'으로 진화함(RL Update).
- **정책 변화(RL Update)**: 보안 및 개인정보 정책에서, 단순 탐지를 넘어 보이지 않는 위협을 선제적으로 차단하는 'Zero Trust 보안 정책'의 핵심 기술로 이상 탐지 알고리즘이 채택됨.
### 매 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.
## 🔗 지식 연결 (Graph)
- [[Time-Series-Analysis|Time-Series-Analysis]], Pattern Recognition, [[Safety & Reliability|Safety & Reliability]], [[Variational Autoencoders (VAE)|Variational Autoencoders (VAE)]], [[Decision Theory|Decision Theory]]
- **Modern Tech/Tools**: Isolation Forest, One-Class SVM, Amazon Lookout for Metrics.
---
### 매 응용
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.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Isolation Forest baseline
```python
from sklearn.ensemble import IsolationForest
import numpy as np
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# 매 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
```
## 🤔 의사결정 기준 (Decision Criteria)
### 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)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 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))
**선택 B를 써야 할 때:**
- *(TODO)*
# 매 train on normal only — anomaly = high reconstruction error
recon = model(x)
score = ((x - recon) ** 2).mean(dim=1)
```
**기본값:**
> *(TODO)*
### 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
```
## ❌ 안티패턴 (Anti-Patterns)
### PyOD ensemble
```python
from pyod.models.iforest import IForest
from pyod.models.lof import LOF
from pyod.models.combination import average
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
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 |