Master statistical methods, isolation forests, and autoencoders
An anomaly (outlier) is a data point that deviates significantly from the expected pattern. Anomalies can be:
Requirement: Labeled anomalies
Use: Fraud with historical labels
Requirement: Only normal data for training
Use: Manufacturing quality control
Requirement: No labels at all
Use: Exploratory analysis
For normally distributed data:
\[z = \frac{x - \mu}{\sigma}\]
Flag as anomaly if \(|z| > 3\) (3-sigma rule)
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\)
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
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\)
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)
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.
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}\]
Advantages:
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
)
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.
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
When to use:
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
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.
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:
Rule of thumb: Bottleneck = 10-30% of input dimension
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)
Individual timestamps that deviate:
Patterns that are anomalous:
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)
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}")
Multi-layered approach:
Key considerations:
Isolation Forest advantages:
One-Class SVM advantages:
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:
Best practice: Use precision-recall curve to understand trade-offs, then set threshold based on business acceptable false positive rate.
Mechanism:
Why it works: The model learns to "remember" normal patterns. Anomalies are patterns it never learned to encode/decode efficiently.
Variants:
Types of drift:
Mitigation strategies: