Machine Learning | Anomaly Detection

Master statistical methods, isolation forests, and autoencoders

Table of Contents
  1. Anomaly Detection Fundamentals
  2. Statistical Methods
  3. Isolation Forest
  4. One-Class SVM
  5. Autoencoders for Anomaly Detection
  6. Time Series Anomaly Detection
  7. Evaluation Strategies
  8. Interview Questions

Anomaly Detection Fundamentals

What is an Anomaly?

An anomaly (outlier) is a data point that deviates significantly from the expected pattern. Anomalies can be:

  • Point Anomalies: Single data points that are abnormal (e.g., fraudulent transaction)
  • Contextual Anomalies: Normal in one context, abnormal in another (e.g., high AC usage in winter)
  • Collective Anomalies: Group of points that together form an anomaly (e.g., DDoS attack pattern)
Supervised

Requirement: Labeled anomalies

  • Train classifier on normal vs anomaly
  • Handle class imbalance
  • Best accuracy when labels exist

Use: Fraud with historical labels

Semi-Supervised

Requirement: Only normal data for training

  • Learn normal pattern
  • Flag deviations as anomalies
  • Most common in practice

Use: Manufacturing quality control

Unsupervised

Requirement: No labels at all

  • Assume anomalies are rare
  • Find statistical outliers
  • Requires careful threshold tuning

Use: Exploratory analysis

Statistical Methods

Z-Score Method

For normally distributed data:

\[z = \frac{x - \mu}{\sigma}\]

Flag as anomaly if \(|z| > 3\) (3-sigma rule)

  • Simple and interpretable
  • Assumes Gaussian distribution
  • Sensitive to outliers in μ, σ calculation
Modified Z-Score (MAD)

More robust to outliers:

\[M_i = \frac{0.6745 (x_i - \tilde{x})}{\text{MAD}}\]

\[\text{MAD} = \text{median}(|x_i - \tilde{x}|)\]

Flag if \(|M_i| > 3.5\)

IQR Method

Based on quartiles:

\[\text{IQR} = Q_3 - Q_1\]

Anomaly if:

\[x < Q_1 - 1.5 \cdot \text{IQR} \text{ or } x > Q_3 + 1.5 \cdot \text{IQR}\]

No distribution assumption

Mahalanobis Distance

For multivariate data:

\[D_M = \sqrt{(\mathbf{x} - \boldsymbol{\mu})^T \Sigma^{-1} (\mathbf{x} - \boldsymbol{\mu})}\]

Accounts for correlations between features. Under Gaussian assumption, \(D_M^2 \sim \chi^2_p\)

Python Implementation

import numpy as np
from scipy import stats

class StatisticalAnomalyDetector:
    def __init__(self, method='zscore', threshold=3.0):
        self.method = method
        self.threshold = threshold
        self.params = {}

    def fit(self, X):
        """Fit detector on training data (assumed normal)"""
        X = np.array(X)

        if self.method == 'zscore':
            self.params['mean'] = np.mean(X, axis=0)
            self.params['std'] = np.std(X, axis=0)

        elif self.method == 'mad':
            self.params['median'] = np.median(X, axis=0)
            self.params['mad'] = np.median(np.abs(X - self.params['median']), axis=0)

        elif self.method == 'iqr':
            self.params['q1'] = np.percentile(X, 25, axis=0)
            self.params['q3'] = np.percentile(X, 75, axis=0)
            self.params['iqr'] = self.params['q3'] - self.params['q1']

        elif self.method == 'mahalanobis':
            self.params['mean'] = np.mean(X, axis=0)
            self.params['cov_inv'] = np.linalg.inv(np.cov(X.T))

        return self

    def score(self, X):
        """Compute anomaly scores (higher = more anomalous)"""
        X = np.array(X)

        if self.method == 'zscore':
            z = (X - self.params['mean']) / (self.params['std'] + 1e-10)
            return np.max(np.abs(z), axis=1) if X.ndim > 1 else np.abs(z)

        elif self.method == 'mad':
            m = 0.6745 * (X - self.params['median']) / (self.params['mad'] + 1e-10)
            return np.max(np.abs(m), axis=1) if X.ndim > 1 else np.abs(m)

        elif self.method == 'iqr':
            lower = self.params['q1'] - 1.5 * self.params['iqr']
            upper = self.params['q3'] + 1.5 * self.params['iqr']
            # Distance outside bounds
            below = np.maximum(0, lower - X)
            above = np.maximum(0, X - upper)
            deviation = below + above
            return np.max(deviation, axis=1) if X.ndim > 1 else deviation

        elif self.method == 'mahalanobis':
            diff = X - self.params['mean']
            return np.sqrt(np.sum(diff @ self.params['cov_inv'] * diff, axis=1))

    def predict(self, X):
        """Return 1 for anomaly, 0 for normal"""
        scores = self.score(X)
        return (scores > self.threshold).astype(int)

# Usage
detector = StatisticalAnomalyDetector(method='mahalanobis', threshold=3.0)
detector.fit(X_train)  # Train on normal data only
anomalies = detector.predict(X_test)

Isolation Forest

Core Intuition

Anomalies are few and different, so they are easier to isolate. Isolation Forest builds random trees that partition data - anomalies require fewer splits to isolate, resulting in shorter path lengths.

Anomaly Score

Average path length \(E(h(x))\) across trees:

\[s(x, n) = 2^{-\frac{E(h(x))}{c(n)}}\]

Where \(c(n)\) is the average path length in a random BST:

\[c(n) = 2H(n-1) - \frac{2(n-1)}{n}\]

  • \(s \approx 1\): Anomaly (short path)
  • \(s \approx 0.5\): Normal
  • \(s \approx 0\): Very normal (deep in tree)
Key Hyperparameters
  • n_estimators: Number of trees (100-200 typical)
  • max_samples: Subsample size (256 works well)
  • contamination: Expected proportion of anomalies
  • max_features: Features per tree (1.0 = all)

Advantages:

  • Linear time complexity O(n)
  • Works well in high dimensions
  • No distance calculations needed

Python Implementation

from sklearn.ensemble import IsolationForest
import numpy as np

# Train Isolation Forest
iso_forest = IsolationForest(
    n_estimators=100,
    max_samples='auto',  # min(256, n_samples)
    contamination=0.05,  # Expected 5% anomalies
    random_state=42,
    n_jobs=-1
)

# Fit on data (can include anomalies - unsupervised)
iso_forest.fit(X_train)

# Predict: -1 for anomaly, 1 for normal
predictions = iso_forest.predict(X_test)
anomalies = X_test[predictions == -1]

# Get anomaly scores (lower = more anomalous)
scores = iso_forest.decision_function(X_test)
# Convert to anomaly score (higher = more anomalous)
anomaly_scores = -scores

# For threshold tuning, use score_samples
raw_scores = iso_forest.score_samples(X_test)

# Custom threshold based on percentile
threshold = np.percentile(anomaly_scores, 95)
custom_anomalies = anomaly_scores > threshold

# Feature importance (approximate via permutation)
from sklearn.inspection import permutation_importance

# Need labels for this - use predictions as proxy
y_pred = (predictions == -1).astype(int)
perm_importance = permutation_importance(
    iso_forest, X_test, y_pred,
    n_repeats=10, random_state=42
)
Interview Tip

Why max_samples=256? The original paper shows that subsampling improves performance by: (1) reducing swamping (normal points masked by anomalies), (2) reducing masking (anomalies hidden by normal points), and (3) faster training. 256 is empirically optimal across many datasets.

One-Class SVM

Objective

Find a hyperplane that separates data from origin with maximum margin:

\[\min_{\mathbf{w}, \rho, \boldsymbol{\xi}} \frac{1}{2}\|\mathbf{w}\|^2 + \frac{1}{\nu n}\sum_i \xi_i - \rho\]

Subject to:

\[\mathbf{w}^T \phi(\mathbf{x}_i) \geq \rho - \xi_i, \quad \xi_i \geq 0\]

\(\nu\) controls the fraction of outliers

Key Parameters
  • nu (ν): Upper bound on fraction of outliers, lower bound on fraction of support vectors
  • kernel: RBF most common for anomaly detection
  • gamma: RBF kernel coefficient (higher = tighter boundary)

When to use:

  • Small to medium datasets
  • Clear boundary needed
  • Semi-supervised (train on normal only)
from sklearn.svm import OneClassSVM
from sklearn.preprocessing import StandardScaler

# Scale data (important for SVM)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# Train One-Class SVM
ocsvm = OneClassSVM(
    kernel='rbf',
    gamma='scale',  # 1 / (n_features * X.var())
    nu=0.05,        # Expected outlier fraction
)
ocsvm.fit(X_train_scaled)  # Train on NORMAL data only

# Predict
predictions = ocsvm.predict(X_test_scaled)  # -1 = anomaly, 1 = normal
scores = ocsvm.decision_function(X_test_scaled)  # Distance to boundary

# Negative score = anomaly (outside boundary)
anomaly_mask = predictions == -1

Autoencoders for Anomaly Detection

Core Idea

Train an autoencoder to reconstruct normal data. Since it learns the "normal" manifold, anomalies will have high reconstruction error because they don't fit the learned patterns.

Reconstruction Error

For input \(\mathbf{x}\) and reconstruction \(\hat{\mathbf{x}}\):

\[\text{MSE} = \|\mathbf{x} - \hat{\mathbf{x}}\|_2^2\]

Anomaly if MSE > threshold (e.g., 95th percentile on validation set)

Alternative losses:

  • MAE: More robust to outliers
  • Cosine: For normalized data
  • Binary CE: For binary features
Architecture Choices
  • Bottleneck size: Too small = underfitting, too large = memorization
  • Depth: Deeper for complex patterns
  • Regularization: Dropout, L2, sparse activations
  • Variational (VAE): Probabilistic, better generalization

Rule of thumb: Bottleneck = 10-30% of input dimension

PyTorch Implementation

import torch
import torch.nn as nn
import numpy as np

class AnomalyAutoencoder(nn.Module):
    def __init__(self, input_dim, encoding_dim=32):
        super().__init__()

        # Encoder
        self.encoder = nn.Sequential(
            nn.Linear(input_dim, 128),
            nn.ReLU(),
            nn.Dropout(0.2),
            nn.Linear(128, 64),
            nn.ReLU(),
            nn.Linear(64, encoding_dim)
        )

        # Decoder
        self.decoder = nn.Sequential(
            nn.Linear(encoding_dim, 64),
            nn.ReLU(),
            nn.Linear(64, 128),
            nn.ReLU(),
            nn.Dropout(0.2),
            nn.Linear(128, input_dim)
        )

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

    def reconstruction_error(self, x):
        with torch.no_grad():
            x_recon = self.forward(x)
            # Per-sample MSE
            mse = torch.mean((x - x_recon) ** 2, dim=1)
        return mse

class AnomalyDetector:
    def __init__(self, input_dim, encoding_dim=32, threshold_percentile=95):
        self.model = AnomalyAutoencoder(input_dim, encoding_dim)
        self.threshold = None
        self.threshold_percentile = threshold_percentile

    def fit(self, X_train, epochs=100, batch_size=32, lr=0.001):
        """Train on NORMAL data only"""
        self.model.train()
        optimizer = torch.optim.Adam(self.model.parameters(), lr=lr)
        criterion = nn.MSELoss()

        X_tensor = torch.FloatTensor(X_train)
        dataset = torch.utils.data.TensorDataset(X_tensor, X_tensor)
        loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True)

        for epoch in range(epochs):
            total_loss = 0
            for batch_x, _ in loader:
                optimizer.zero_grad()
                recon = self.model(batch_x)
                loss = criterion(recon, batch_x)
                loss.backward()
                optimizer.step()
                total_loss += loss.item()

            if (epoch + 1) % 20 == 0:
                print(f"Epoch {epoch+1}: Loss = {total_loss/len(loader):.6f}")

        # Set threshold based on training data reconstruction errors
        self.model.eval()
        train_errors = self.model.reconstruction_error(X_tensor).numpy()
        self.threshold = np.percentile(train_errors, self.threshold_percentile)

    def predict(self, X):
        """Return 1 for anomaly, 0 for normal"""
        self.model.eval()
        X_tensor = torch.FloatTensor(X)
        errors = self.model.reconstruction_error(X_tensor).numpy()
        return (errors > self.threshold).astype(int)

    def score(self, X):
        """Return reconstruction error (anomaly score)"""
        self.model.eval()
        X_tensor = torch.FloatTensor(X)
        return self.model.reconstruction_error(X_tensor).numpy()

# Usage
detector = AnomalyDetector(input_dim=X_train.shape[1], encoding_dim=16)
detector.fit(X_train_normal, epochs=100)
anomaly_predictions = detector.predict(X_test)
anomaly_scores = detector.score(X_test)

Time Series Anomaly Detection

Point Anomalies

Individual timestamps that deviate:

  • Rolling statistics (mean, std) with Z-score
  • Exponential weighted moving average (EWMA)
  • Prophet with uncertainty intervals
  • ARIMA residuals analysis
Contextual/Collective

Patterns that are anomalous:

  • Sliding window + clustering
  • LSTM autoencoders
  • Spectral residual (SR)
  • Matrix Profile

Time Series Anomaly Detection Methods

import numpy as np
import pandas as pd

class TimeSeriesAnomalyDetector:
    """Multiple methods for time series anomaly detection"""

    @staticmethod
    def rolling_zscore(series, window=20, threshold=3.0):
        """Rolling window Z-score method"""
        rolling_mean = series.rolling(window=window, center=True).mean()
        rolling_std = series.rolling(window=window, center=True).std()

        z_scores = (series - rolling_mean) / (rolling_std + 1e-10)
        anomalies = np.abs(z_scores) > threshold

        return anomalies, z_scores

    @staticmethod
    def ewma_method(series, span=20, threshold=3.0):
        """Exponentially Weighted Moving Average"""
        ewma = series.ewm(span=span).mean()
        ewma_std = series.ewm(span=span).std()

        deviation = (series - ewma) / (ewma_std + 1e-10)
        anomalies = np.abs(deviation) > threshold

        return anomalies, deviation

    @staticmethod
    def isolation_forest_sliding(series, window_size=10, contamination=0.05):
        """Apply Isolation Forest on sliding windows"""
        from sklearn.ensemble import IsolationForest

        # Create sliding window features
        windows = []
        for i in range(len(series) - window_size + 1):
            windows.append(series.iloc[i:i+window_size].values)

        X = np.array(windows)

        # Fit Isolation Forest
        iso = IsolationForest(contamination=contamination, random_state=42)
        predictions = iso.fit_predict(X)

        # Map back to original indices (center of window)
        anomalies = np.zeros(len(series), dtype=bool)
        offset = window_size // 2
        for i, pred in enumerate(predictions):
            if pred == -1:
                anomalies[i + offset] = True

        return anomalies, iso.decision_function(X)

    @staticmethod
    def prophet_anomaly(df, interval_width=0.95):
        """Use Prophet's uncertainty intervals"""
        from prophet import Prophet

        # Prophet expects 'ds' and 'y' columns
        model = Prophet(interval_width=interval_width)
        model.fit(df)

        forecast = model.predict(df)

        # Anomaly if actual outside prediction interval
        anomalies = (df['y'].values < forecast['yhat_lower'].values) | \
                    (df['y'].values > forecast['yhat_upper'].values)

        return anomalies, forecast

# LSTM Autoencoder for sequence anomalies
class LSTMAutoencoder(nn.Module):
    def __init__(self, input_dim, hidden_dim=64, n_layers=2):
        super().__init__()

        self.encoder = nn.LSTM(
            input_dim, hidden_dim, n_layers,
            batch_first=True, dropout=0.2
        )

        self.decoder = nn.LSTM(
            hidden_dim, hidden_dim, n_layers,
            batch_first=True, dropout=0.2
        )

        self.output = nn.Linear(hidden_dim, input_dim)

    def forward(self, x):
        # Encode
        _, (hidden, cell) = self.encoder(x)

        # Decode (reconstruct sequence)
        seq_len = x.size(1)
        decoder_input = hidden[-1].unsqueeze(1).repeat(1, seq_len, 1)
        decoder_output, _ = self.decoder(decoder_input, (hidden, cell))

        reconstruction = self.output(decoder_output)
        return reconstruction

# Usage for sequence anomalies
def create_sequences(data, seq_length):
    sequences = []
    for i in range(len(data) - seq_length + 1):
        sequences.append(data[i:i+seq_length])
    return np.array(sequences)

Evaluation Strategies

Key Metrics
  • Precision: Of detected anomalies, how many are true?
  • Recall: Of true anomalies, how many detected?
  • F1-Score: Harmonic mean of precision/recall
  • PR-AUC: Better than ROC-AUC for imbalanced data
  • Average Precision: Area under precision-recall curve
Common Pitfalls
  • Accuracy is misleading: 99% accuracy is useless if 1% anomaly rate
  • Threshold sensitivity: Report metrics at multiple thresholds
  • Temporal leakage: Don't train on future data
  • Label quality: Many "anomalies" may be mislabeled normal
from sklearn.metrics import (
    precision_recall_curve, average_precision_score,
    f1_score, precision_score, recall_score,
    roc_auc_score
)
import matplotlib.pyplot as plt

def evaluate_anomaly_detector(y_true, y_scores, y_pred=None):
    """Comprehensive evaluation of anomaly detector"""

    results = {}

    # AUC metrics (threshold-independent)
    results['roc_auc'] = roc_auc_score(y_true, y_scores)
    results['pr_auc'] = average_precision_score(y_true, y_scores)

    # Precision-Recall curve
    precision, recall, thresholds = precision_recall_curve(y_true, y_scores)

    # Find best F1 threshold
    f1_scores = 2 * (precision * recall) / (precision + recall + 1e-10)
    best_idx = np.argmax(f1_scores)
    results['best_threshold'] = thresholds[best_idx] if best_idx < len(thresholds) else thresholds[-1]
    results['best_f1'] = f1_scores[best_idx]

    # If predictions provided, compute point metrics
    if y_pred is not None:
        results['precision'] = precision_score(y_true, y_pred)
        results['recall'] = recall_score(y_true, y_pred)
        results['f1'] = f1_score(y_true, y_pred)

    # Plot PR curve
    plt.figure(figsize=(8, 6))
    plt.plot(recall, precision, 'b-', label=f'PR curve (AP={results["pr_auc"]:.3f})')
    plt.scatter(recall[best_idx], precision[best_idx], color='red', s=100,
                label=f'Best F1={results["best_f1"]:.3f}')
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.title('Precision-Recall Curve')
    plt.legend()
    plt.grid(True)

    return results

# Example
results = evaluate_anomaly_detector(y_true, anomaly_scores, y_pred)
print(f"PR-AUC: {results['pr_auc']:.4f}")
print(f"Best F1: {results['best_f1']:.4f} at threshold {results['best_threshold']:.4f}")

Interview Questions

Multi-layered approach:

  1. Rule-based layer: Known fraud patterns (velocity checks, blocklists)
  2. Supervised model: Train on labeled fraud cases (XGBoost, neural network)
  3. Unsupervised layer: Isolation Forest or autoencoder for novel fraud

Key considerations:

  • Extreme class imbalance (0.1% fraud) - use PR-AUC, SMOTE, class weights
  • Concept drift - fraud patterns evolve, need continuous retraining
  • Real-time requirements - feature computation latency matters
  • Feedback loop - incorporate analyst decisions into training
  • Cost-sensitive - weigh false negatives (missed fraud) vs false positives (customer friction)

Isolation Forest advantages:

  • Scales well to large datasets (linear complexity)
  • Works in high dimensions
  • Handles mixed data types better
  • Truly unsupervised - can handle data with anomalies

One-Class SVM advantages:

  • Well-defined decision boundary
  • Works well for semi-supervised (clean training data)
  • Better for smaller datasets with clear structure
  • Kernel flexibility for non-linear boundaries

General rule: Start with Isolation Forest for most cases. Use One-Class SVM when you have clean training data and need interpretable boundaries.

Methods for threshold selection:

  1. Business constraint: "We can only investigate 100 alerts/day" → set threshold to top 100
  2. Contamination estimate: If ~5% expected anomalies, use 95th percentile
  3. Validation set: Optimize F1 on labeled validation data
  4. Statistical: Mean + 3σ of scores on normal data
  5. Knee/elbow method: Find where score distribution changes slope

Best practice: Use precision-recall curve to understand trade-offs, then set threshold based on business acceptable false positive rate.

Mechanism:

  1. Train autoencoder to compress and reconstruct normal data
  2. The bottleneck forces it to learn a compressed representation of normal patterns
  3. At inference, anomalies don't fit the learned normal manifold
  4. Reconstruction error is high for anomalies

Why it works: The model learns to "remember" normal patterns. Anomalies are patterns it never learned to encode/decode efficiently.

Variants:

  • VAE: Probabilistic, can detect anomalies via low likelihood
  • Sparse AE: Forces selective activation, better feature learning
  • Denoising AE: More robust to noise
  • LSTM-AE: For sequential/time series data

Types of drift:

  • Feature drift: Input distribution changes (e.g., seasonal patterns)
  • Label drift: What's "anomalous" changes (e.g., new fraud patterns)

Mitigation strategies:

  1. Sliding window: Retrain periodically on recent data
  2. Online learning: Continuously update model with new labeled examples
  3. Drift detection: Monitor input distribution, trigger retraining when drift detected
  4. Ensemble: Combine models trained on different time windows
  5. Adaptive thresholds: Recalibrate threshold based on recent score distribution
Previous: Recommender Systems Next: Clustering