🤖 AI/ML

Anomaly Detection

Anomaly Detection

Identifying data that deviates from normal patterns. Fraud detection, failure detection.

📖 Detailed Explanation

Anomaly Detection is a Machine Learning technique that automatically identifies observations that differ significantly from the majority of normal patterns in a dataset. It plays a key role in a variety of fields, including fraud transaction detection, network intrusion detection, manufacturing defect detection, and medical abnormality diagnosis. Anomalies often account for less than 1% of the total data, so techniques for handling the extreme class imbalance problem are needed.

Anomaly detection techniques are broadly classified into three types: (1) Unsupervised learning - training only on normal data to detect points that deviate from the normal distribution (Isolation Forest, One-Class SVM, Autoencoder), (2) Supervised learning - training a classifier on data with anomaly/normal labels, (3) Semi-supervised learning - training first on normal data, then determining whether new data is anomalous. In practice, labels are difficult to obtain, so unsupervised/semi-supervised approaches are mainly used.

Among the core algorithms of modern anomaly detection systems, Isolation Forest takes advantage of the fact that anomalies are "easier to isolate" than normal data. When random partitioning is repeated, anomalies are isolated with fewer partitions, so points with a short average path length are judged to be anomalies. With O(n log n) time complexity, it is efficient even for large-scale data, and it can be used right away in scikit-learn.

The biggest challenge in building an anomaly detection system in practice is evaluation. Because anomalies are extremely rare, Accuracy is meaningless, and Precision-Recall AUC or F1-score should be used. The 2024-2025 trends are Deep Learning-based methods (VAE, Transformer Autoencoder) and time-series-specific models (LSTM-AE, Temporal Fusion Transformer), and managed services such as AWS Lookout and Azure Anomaly Detector are also popular.

💻 Code Example

# 이상치 탐지 실전 예제: Isolation Forest + Autoencoder
# pip install scikit-learn torch numpy pandas

import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report, precision_recall_curve, auc

# 1. Isolation Forest - 가장 널리 사용되는 방법
def isolation_forest_detection(X_train, X_test, contamination=0.01):
    """
    contamination: 예상 이상치 비율 (기본 1%)
    """
    scaler = StandardScaler()
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)

    # 모델 학습 (정상 데이터로만)
    iso_forest = IsolationForest(
        n_estimators=100,
        contamination=contamination,
        random_state=42,
        n_jobs=-1
    )
    iso_forest.fit(X_train_scaled)

    # 예측: -1=이상치, 1=정상
    predictions = iso_forest.predict(X_test_scaled)
    # 이상치 점수 (낮을수록 이상치)
    scores = iso_forest.decision_function(X_test_scaled)

    return predictions, scores

# 2. PyTorch Autoencoder 기반 이상치 탐지
import torch
import torch.nn as nn

class AnomalyAutoencoder(nn.Module):
    def __init__(self, input_dim, latent_dim=8):
        super().__init__()
        self.encoder = nn.Sequential(
            nn.Linear(input_dim, 64),
            nn.ReLU(),
            nn.Linear(64, 32),
            nn.ReLU(),
            nn.Linear(32, latent_dim)
        )
        self.decoder = nn.Sequential(
            nn.Linear(latent_dim, 32),
            nn.ReLU(),
            nn.Linear(32, 64),
            nn.ReLU(),
            nn.Linear(64, input_dim)
        )

    def forward(self, x):
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return decoded

    def detect_anomalies(self, x, threshold):
        """재구성 오차가 threshold를 넘으면 이상치"""
        with torch.no_grad():
            reconstructed = self.forward(x)
            mse = ((x - reconstructed) ** 2).mean(dim=1)
            return mse > threshold, mse

# 실행 예시
if __name__ == "__main__":
    # 샘플 데이터 생성
    np.random.seed(42)
    normal_data = np.random.randn(1000, 10)  # 정상 데이터
    anomaly_data = np.random.randn(20, 10) + 5  # 이상치

    X_train = normal_data[:800]
    X_test = np.vstack([normal_data[800:], anomaly_data])
    y_test = np.array([0]*200 + [1]*20)  # 0=정상, 1=이상

    # Isolation Forest 실행
    preds, scores = isolation_forest_detection(X_train, X_test)
    preds_binary = (preds == -1).astype(int)

    print("=== Isolation Forest 결과 ===")
    print(classification_report(y_test, preds_binary,
                                target_names=['정상', '이상치']))

📊 Performance & Cost

Algorithm/Service Strengths Weaknesses Recommended Situations
Isolation Forest Fast, easy to interpret Performance degrades in high dimensions Structured data, fast deployment
Autoencoder Learns complex patterns Requires tuning, slow Images, time series
One-Class SVM Effective on small-scale data Slow on large-scale data When data is scarce
AWS Lookout for Metrics Managed, automated Cost ($0.75/1K data points) AWS environments, fast setup
Azure Anomaly Detector Time-series-specific, simple $0.157/1K calls Azure environments, time series

* Pricing and characteristics as of January 2025

🗣️ Say It Like This in Practice

💬 In a Meeting
"A 99% accuracy in fraud detection is meaningless. Fraudulent transactions are only 0.1%. You need to evaluate with Precision-Recall AUC and adjust the threshold in consideration of business impact. If there are many false positives (False Positive), customer complaints increase, and if there are many false negatives (False Negative), you miss actual fraud."
💬 In an Interview
"Isolation Forest is based on the assumption that anomalies are 'easy to isolate.' When data is recursively partitioned by selecting random features and split points, anomalies are isolated with fewer partitions. If the average path length is short, it is judged to be an anomaly, and with O(n log n) time complexity, it is efficient even for large-scale data."
💬 In a Technical Discussion
"Time-series anomaly detection is different from static methods. You have to take seasonality, trend, and periodicity into account, so LSTM Autoencoder or Transformer-based models are effective. Recently, newer architectures such as Temporal Fusion Transformer and N-BEATS are also widely used."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Evaluating the model with Accuracy

If anomalies are 1%, predicting "all normal" still gives 99% accuracy. Use Precision, Recall, F1-score, and PR-AUC.

❌
Setting the contamination parameter arbitrarily

Isolation Forest's contamination is the expected proportion of anomalies, but if it does not match the actual data, performance drops sharply. Estimate it using domain knowledge or preliminary analysis.

✅
The right approach: collaborate with domain experts and build a feedback loop

Anomaly detection models need continuous feedback even after deployment. Build an MLOps pipeline in which experts review the detected anomalies, and false positive/false negative cases are collected to improve the model.

🔗 Related Terms

📚 Learn More