This is a great request for building an anomaly detection system using autoencoders. Let me create a comprehensive solution that includes:
- A PyTorch autoencoder model
- Training on normal data only
- Calculating reconstruction error
- Setting a threshold based on 99th percentile
- Anomaly detection using this threshold
- Visualization and evaluation
- Example usage with synthetic data
Let me build this step by step with good practices and explanations.
Anomaly Detection with PyTorch Autoencoder
I'll build a complete anomaly detection system using autoencoders trained on normal data only.
1. Core Autoencoder Model and Training
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_blobs
import seaborn as sns
class Autoencoder(nn.Module):
"""Neural network autoencoder for anomaly detection"""
def __init__(self, input_dim, hidden_dims=[64, 32, 16]):
super(Autoencoder, self).__init__()
# Encoder
encoder_layers = []
prev_dim = input_dim
for hidden_dim in hidden_dims:
encoder_layers.extend([
nn.Linear(prev_dim, hidden_dim),
nn.ReLU(),
nn.BatchNorm1d(hidden_dim)
])
prev_dim = hidden_dim
self.encoder = nn.Sequential(*encoder_layers)
# Decoder (mirror of encoder)
decoder_layers = []
hidden_dims_reversed = hidden_dims[::-1]
for i, hidden_dim in enumerate(hidden_dims_reversed):
next_dim = hidden_dims_reversed[i + 1] if i + 1 < len(hidden_dims_reversed) else input_dim
decoder_layers.extend([
nn.Linear(hidden_dim, next_dim),
nn.ReLU() if i + 1 < len(hidden_dims_reversed) else nn.Identity(),
nn.BatchNorm1d(next_dim) if i + 1 < len(hidden_dims_reversed) else nn.Identity()
])
self.decoder = nn.Sequential(*decoder_layers)
def forward(self, x):
"""Forward pass through autoencoder"""
encoded = self.encoder(x)
decoded = self.decoder(encoded)
return decoded
def encode(self, x):
"""Get latent representation"""
return self.encoder(x)
class AnomalyDetector:
"""Autoencoder-based anomaly detector"""
def __init__(self, input_dim, hidden_dims=[64, 32, 16], device=None):
self.device = device or torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.model = Autoencoder(input_dim, hidden_dims).to(self.device)
self.scaler = StandardScaler()
self.threshold = None
self.training_errors = None
def _compute_reconstruction_error(self, x):
"""Compute MSE reconstruction error"""
with torch.no_grad():
x_tensor = torch.FloatTensor(x).to(self.device)
reconstructed = self.model(x_tensor)
error = torch.mean((x_tensor - reconstructed) ** 2, dim=1)
return error.cpu().numpy()
def train(self, X_train, epochs=100, batch_size=32, lr=0.001,
validation_split=0.2, verbose=True):
"""
Train autoencoder on normal data only
Args:
X_train: Training data (normal samples only)
epochs: Number of training epochs
batch_size: Batch size for training
lr: Learning rate
validation_split: Fraction of data for validation
verbose: Print training progress
"""
# Normalize data
X_train = self.scaler.fit_transform(X_train)
X_train = torch.FloatTensor(X_train)
# Split into train/val
n_samples = len(X_train)
n_train = int(n_samples * (1 - validation_split))
indices = torch.randperm(n_samples)
train_indices = indices[:n_train]
val_indices = indices[n_train:]
X_train_split = X_train[train_indices]
X_val_split = X_train[val_indices]
# Create data loaders
train_dataset = TensorDataset(X_train_split)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
# Setup optimizer and loss
optimizer = optim.Adam(self.model.parameters(), lr=lr)
criterion = nn.MSELoss()
# Training loop
train_losses = []
val_losses = []
for epoch in range(epochs):
# Training phase
self.model.train()
train_loss = 0.0
for batch in train_loader:
x_batch = batch[0].to(self.device)
# Forward pass
reconstructed = self.model(x_batch)
loss = criterion(x_batch, reconstructed)
# Backward pass
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_loss += loss.item() * x_batch.size(0)
train_loss /= len(X_train_split)
train_losses.append(train_loss)
# Validation phase
self.model.eval()
val_loss = 0.0
with torch.no_grad():
X_val_tensor = X_val_split.to(self.device)
reconstructed = self.model(X_val_tensor)
val_loss = criterion(X_val_tensor, reconstructed).item()
val_losses.append(val_loss)
if verbose and (epoch + 1) % 10 == 0:
print(f"Epoch {epoch + 1}/{epochs} | "
f"Train Loss: {train_loss:.6f} | Val Loss: {val_loss:.6f}")
# Calculate training reconstruction errors for threshold
self.model.eval()
self.training_errors = self._compute_reconstruction_error(
self.scaler.inverse_transform(X_train_split.numpy())
)
return {
'train_losses': train_losses,
'val_losses': val_losses
}
def set_threshold(self, percentile=99):
"""
Set anomaly threshold based on percentile of training errors
Args:
percentile: Percentile for threshold (e.g., 99 = 99th percentile)
"""
if self.training_errors is None:
raise ValueError("Model must be trained first")
self.threshold = np.percentile(self.training_errors, percentile)
print(f"Anomaly threshold set to {self.threshold:.6f} (99th percentile)")
return self.threshold
def predict(self, X, return_scores=False):
"""
Detect anomalies
Args:
X: Input data
return_scores: If True, return reconstruction errors as well
Returns:
anomaly_labels: 1 for anomaly, 0 for normal
reconstruction_errors: (optional) MSE reconstruction error for each sample
"""
if self.threshold is None:
raise ValueError("Threshold not set. Call set_threshold() first")
X_normalized = self.scaler.transform(X)
errors = self._compute_reconstruction_error(X_normalized)
anomalies = (errors > self.threshold).astype(int)
if return_scores:
return anomalies, errors
return anomalies
def get_reconstruction_error(self, X):
"""Get reconstruction error for samples"""
X_normalized = self.scaler.transform(X)
return self._compute_reconstruction_error(X_normalized)
# Example usage with synthetic data
if __name__ == "__main__":
print("=" * 80)
print("ANOMALY DETECTION WITH AUTOENCODER")
print("=" * 80)
# Generate normal training data
np.random.seed(42)
X_normal_train, _ = make_blobs(n_samples=1000, n_features=20, centers=1,
cluster_std=1.0, random_state=42)
# Generate normal test data
X_normal_test, _ = make_blobs(n_samples=200, n_features=20, centers=1,
cluster_std=1.0, random_state=43)
# Generate anomalous data (outliers)
X_anomaly, _ = make_blobs(n_samples=100, n_features=20, centers=1,
cluster_std=3.0, random_state=44)
print(f"\nTraining data shape: {X_normal_train.shape}")
print(f"Normal test data shape: {X_normal_test.shape}")
print(f"Anomaly data shape: {X_anomaly.shape}")
# Initialize and train detector
print("\n" + "=" * 80)
print("TRAINING PHASE")
print("=" * 80)
detector = AnomalyDetector(input_dim=20, hidden_dims=[64, 32, 16])
history = detector.train(X_normal_train, epochs=100, batch_size=32, lr=0.001)
# Set threshold
print("\n" + "=" * 80)
print("THRESHOLD SETTING")
print("=" * 80)
detector.set_threshold(percentile=99)
# Evaluate on test data
print("\n" + "=" * 80)
print("EVALUATION")
print("=" * 80)
# Test on normal data
y_pred_normal, errors_normal = detector.predict(X_normal_test, return_scores=True)
n_anomalies_normal = np.sum(y_pred_normal)
print(f"\nNormal test data:")
print(f" Total samples: {len(X_normal_test)}")
print(f" Flagged as anomaly: {n_anomalies_normal} ({100*n_anomalies_normal/len(X_normal_test):.2f}%)")
print(f" Mean reconstruction error: {errors_normal.mean():.6f}")
print(f" Std reconstruction error: {errors_normal.std():.6f}")
print(f" Min/Max error: {errors_normal.min():.6f} / {errors_normal.max():.6f}")
# Test on anomalous data
y_pred_anomaly, errors_anomaly = detector.predict(X_anomaly, return_scores=True)
n_anomalies_detected = np.sum(y_pred_anomaly)
print(f"\nAnomaly test data:")
print(f" Total samples: {len(X_anomaly)}")
print(f" Flagged as anomaly: {n_anomalies_detected} ({100*n_anomalies_detected/len(X_anomaly):.2f}%)")
print(f" Mean reconstruction error: {errors_anomaly.mean():.6f}")
print(f" Std reconstruction error: {errors_anomaly.std():.6f}")
print(f" Min/Max error: {errors_anomaly.min():.6f} / {errors_anomaly.max():.6f}")
# Calculate metrics
print("\n" + "=" * 80)
print("METRICS")
print("=" * 80)
TP = n_anomalies_detected # True positives
FP = n_anomalies_normal # False positives
TN = len(X_normal_test) - FP # True negatives
FN = len(X_anomaly) - TP # False negatives
sensitivity = TP / (TP + FN) if (TP + FN) > 0 else 0
specificity = TN / (TN + FP) if (TN + FP) > 0 else 0
precision = TP / (TP + FP) if (TP + FP) > 0 else 0
f1_score = 2 * (precision * sensitivity) / (precision + sensitivity) if (precision + sensitivity) > 0 else 0
print(f"Sensitivity (True Positive Rate): {sensitivity:.4f}")
print(f"Specificity (True Negative Rate): {specificity:.4f}")
print(f"Precision: {precision:.4f}")
print(f"F1-Score: {f1_score:.4f}")
2. Visualization Functions
def plot_training_history(history, figsize=(12, 4)):
"""Plot training history"""
fig, axes = plt.subplots(1, 2, figsize=figsize)
axes[0].plot(history['train_losses'], label='Training Loss', linewidth=2)
axes[0].plot(history['val_losses'], label='Validation Loss', linewidth=2)
axes[0].set_xlabel('Epoch')
axes[0].set_ylabel('MSE Loss')
axes[0].set_title('Autoencoder Training History')
axes[0].legend()
axes[0].grid(True, alpha=0.3)
# Log scale
axes[1].semilogy(history['train_losses'], label='Training Loss', linewidth=2)
axes[1].semilogy(history['val_losses'], label='Validation Loss', linewidth=2)
axes[1].set_xlabel('Epoch')
axes[1].set_ylabel('MSE Loss (log scale)')
axes[1].set_title('Autoencoder Training History (Log Scale)')
axes[1].legend()
axes[1].grid(True, alpha=0.3)
plt.tight_layout()
return fig
def plot_reconstruction_errors(detector, X_normal, X_anomaly, figsize=(14, 5)):
"""Plot reconstruction error distributions"""
errors_normal = detector.get_reconstruction_error(X_normal)
errors_anomaly = detector.get_reconstruction_error(X_anomaly)
fig, axes = plt.subplots(1, 3, figsize=figsize)
# Histogram
axes[0].hist(errors_normal, bins=50, alpha=0.7, label='Normal', color='blue', edgecolor='black')
axes[0].hist(errors_anomaly, bins=50, alpha=0.7, label='Anomaly', color='red', edgecolor='black')
axes[0].axvline(detector.threshold, color='green', linestyle='--', linewidth=2, label='Threshold')
axes[0].set_xlabel('Reconstruction Error (MSE)')
axes[0].set_ylabel('Frequency')
axes[0].set_title('Reconstruction Error Distribution')
axes[0].legend()
axes[0].grid(True, alpha=0.3)
# Box plot
data_to_plot = [errors_normal, errors_anomaly]
bp = axes[1].boxplot(data_to_plot, labels=['Normal', 'Anomaly'], patch_artist=True)
bp['boxes'][0].set_facecolor('blue')
bp['boxes'][1].set_facecolor('red')
axes[1].axhline(detector.threshold, color='green', linestyle='--', linewidth=2, label='Threshold')
axes[1].set_ylabel('Reconstruction Error (MSE)')
axes[1].set_title('Error Box Plot')
axes[1].legend()
axes[1].grid(True, alpha=0.3, axis='y')
# KDE plot
from scipy.stats import gaussian_kde
x_range = np.linspace(0, max(errors_normal.max(), errors_anomaly.max()) * 1.1, 1000)
if len(errors_normal) > 1:
kde_normal = gaussian_kde(errors_normal)
axes[2].plot(x_range, kde_normal(x_range), label='Normal', linewidth=2, color='blue')
axes[2].fill_between(x_range, kde_normal(x_range), alpha=0.3, color='blue')
if len(errors_anomaly) > 1:
kde_anomaly = gaussian_kde(errors_anomaly)
axes[2].plot(x_range, kde_anomaly(x_range), label='Anomaly', linewidth=2, color='red')
axes[2].fill_between(x_range, kde_anomaly(x_range), alpha=0.3, color='red')
axes[2].axvline(detector.threshold, color='green', linestyle='--', linewidth=2, label='Threshold')
axes[2].set_xlabel('Reconstruction Error (MSE)')
axes[2].set_ylabel('Density')
axes[2].set_title('Error Distribution (KDE)')
axes[2].legend()
axes[2].grid(True, alpha=0.3)
plt.tight_layout()
return fig
def plot_roc_curve(detector, X_normal, X_anomaly):
"""Plot ROC curve"""
from sklearn.metrics import roc_curve, auc
errors_normal = detector.get_reconstruction_error(X_normal)
errors_anomaly = detector.get_reconstruction_error(X_anomaly)
# Create labels
y_true = np.concatenate([np.zeros(len(X_normal)), np.ones(len(X_anomaly))])
y_scores = np.concatenate([errors_normal, errors_anomaly])
fpr, tpr, thresholds = roc_curve(y_true, y_scores)
roc_auc = auc(fpr, tpr)
fig, ax = plt.subplots(figsize=(8, 7))
ax.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (AUC = {roc_auc:.3f})')
ax.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--', label='Random Classifier')
# Mark current threshold
idx_threshold = np.argmin(np.abs(thresholds - detector.threshold))
ax.plot(fpr[idx_threshold], tpr[idx_threshold], 'go', markersize=10, label='Current Threshold')
ax.set_xlim([0.0, 1.0])
ax.set_ylim([0.0, 1.05])
ax.set_xlabel('False Positive Rate')
ax.set_ylabel('True Positive Rate')
ax.set_title('ROC Curve')
ax.legend(loc="lower right")
ax.grid(True, alpha=0.3)
plt.tight_layout()
return fig
def plot_latent_space(detector, X_normal, X_anomaly, figsize=(10, 8)):
"""Plot 2D projection of latent space"""
from sklearn.decomposition import PCA
# Get latent representations
with torch.no_grad():
X_normal_norm = torch.FloatTensor(detector.scaler.transform(X_normal)).to(detector.device)
X_anomaly_norm = torch.FloatTensor(detector.scaler.transform(X_anomaly)).to(detector.device)
latent_normal = detector.model.encode(X_normal_norm).cpu().numpy()
latent_anomaly = detector.model.encode(X_anomaly_norm).cpu().numpy()
# PCA to 2D
pca = PCA(n_components=2)
latent_all = np.vstack([latent_normal, latent_anomaly])
latent_2d = pca.fit_transform(latent_all)
latent_normal_2d = latent_2d[:len(latent_normal)]
latent_anomaly_2d = latent_2d[len(latent_normal):]
fig, ax = plt.subplots(figsize=figsize)
ax.scatter(latent_normal_2d[:, 0], latent_normal_2d[:, 1],
c='blue', alpha=0.6, s=50, label='Normal', edgecolors='black', linewidth=0.5)
ax.scatter(latent_anomaly_2d[:, 0], latent_anomaly_2d[:, 1],
c='red', alpha=0.6, s=50, label='Anomaly', edgecolors='black', linewidth=0.5)
ax.set_xlabel(f'PC1 ({pca.explained_variance_ratio_[0]:.2%} variance)')
ax.set_ylabel(f'PC2 ({pca.explained_variance_ratio_[1]:.2%} variance)')
ax.set_title('Latent Space Visualization (PCA)')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
return fig
# Generate visualizations
if __name__ == "__main__":
# Plot training history
fig1 = plot_training_history(history)
plt.savefig('training_history.png', dpi=150, bbox_inches='tight')
plt.show()
# Plot reconstruction errors
fig2 = plot_reconstruction_errors(detector, X_normal_test, X_anomaly)
plt.savefig('reconstruction_errors.png', dpi=150, bbox_inches='tight')
plt.show()
# Plot ROC curve
fig3 = plot_roc_curve(detector, X_normal_test, X_anomaly)
plt.savefig('roc_curve.png', dpi=150, bbox_inches='tight')
plt.show()
# Plot latent space
fig4 = plot_latent_space(detector, X_normal_test, X_anomaly)
plt.savefig('latent_space.png', dpi=150, bbox_inches='tight')
plt.show()
3. Advanced Features and Utilities
class AdvancedAnomalyDetector(AnomalyDetector):
"""Enhanced anomaly detector with additional features"""
def adaptive_threshold(self, X_new, percentile=99, update_rate=0.1):
"""
Adaptively update threshold based on new data
Args:
X_new: New normal data samples
percentile: Percentile for threshold
update_rate: How much to weight new data (0-1)
"""
errors_new = self.get_reconstruction_error(X_new)
threshold_new = np.percentile(errors_new, percentile)
# Exponential moving average
self.threshold = (1 - update_rate) * self.threshold + update_rate * threshold_new
print(f"Threshold updated to {self.threshold:.6f}")
return self.threshold
def get_anomaly_details(self, X, top_n=5):
"""
Get detailed information about anomalies
Args:
X: Input data
top_n: Number of top anomalies to return
Returns:
DataFrame with anomaly details
"""
import pandas as pd
predictions, errors = self.predict(X, return_scores=True)
anomaly_indices = np.where(predictions == 1)[0]
sorted_indices = anomaly_indices[np.argsort(errors[anomaly_indices])[::-1]][:top_n]
details = []
for idx in sorted_indices:
details.append({
'sample_index': idx,
'reconstruction_error': errors[idx],
'error_percentile': 100 * np.sum(self.training_errors <= errors[idx]) / len(self.training_errors),
'threshold_ratio': errors[idx] / self.threshold
})
return pd.DataFrame(details)
def explain_anomaly(self, X_sample_idx):
"""
Explain why a sample is anomalous
Args:
X_sample_idx: Index of sample to explain
Returns:
Feature importance scores
"""
X_sample = torch.FloatTensor(self.scaler.transform(X_sample.reshape(1, -1))).to(self.device)
X_sample.requires_grad_(True)
reconstructed = self.model(X_sample)
loss = torch.mean((X_sample - reconstructed) ** 2)
loss.backward()
gradients = X_sample.grad.abs().cpu().numpy().flatten()
return gradients
def plot_reconstruction_comparison(self, X_sample_idx, X, figsize=(14, 4)):
"""Compare original and reconstructed sample"""
with torch.no_grad():
X_norm = torch.FloatTensor(self.scaler.transform(X)).to(self.device)
reconstructed = self.model(X_norm).cpu().numpy()
original = self.scaler.inverse_transform(X_norm.cpu().numpy())
X_original = original[X_sample_idx]
X_reconstructed = self.scaler.inverse_transform(reconstructed)[X_sample_idx]
error_per_feature = np.abs(X_original - X_reconstructed)
fig, axes = plt.subplots(1, 3, figsize=figsize)
# Original
axes[0].bar(range(len(X_original)), X_original, color='blue', alpha=0.7, edgecolor='black')
axes[0].set_title('Original Sample')
axes[0].set_ylabel('Feature Value')
axes[0].grid(True, alpha=0.3, axis='y')
# Reconstructed
axes[1].bar(range(len(X_reconstructed)), X_reconstructed, color='green', alpha=0.7, edgecolor='black')
axes[1].set_title('Reconstructed Sample')
axes[1].set_ylabel('Feature Value')
axes[1].grid(True, alpha=0.3, axis='y')
# Reconstruction error per feature
colors = plt.cm.RdYlGn_r(error_per_feature / error_per_feature.max())
axes[2].bar(range(len(error_per_feature)), error_per_feature, color=colors, edgecolor='black')
axes[2].set_title('Reconstruction Error per Feature')
axes[2].set_ylabel('Error')
axes[2].grid(True, alpha=0.3, axis='y')
plt.tight_layout()
return fig
def batch_predict_with_confidence(detector, X_batch, batch_size=32):
"""
Make predictions with confidence scores
Args:
detector: AnomalyDetector instance
X_batch: Input data
batch_size: Batch size for processing
Returns:
predictions: Anomaly labels
confidence: Confidence scores (0-1)
"""
all_errors = []
predictions_list = []
for i in range(0, len(X_batch), batch_size):
batch = X_batch[i:i+batch_size]
preds, errors = detector.predict(batch, return_scores=True)
predictions_list.append(preds)
all_errors.append(errors)
predictions = np.concatenate(predictions_list)
errors = np.concatenate(all_errors)
# Confidence as distance from threshold (normalized)
confidence = np.abs(errors - detector.threshold) / (detector.threshold + 1e-10)
confidence = np.clip(confidence, 0, 1)
return predictions, confidence, errors
def find_optimal_threshold(detector, X_normal_val, X_anomaly_val, metric='f1'):
"""
Find optimal threshold using validation data
Args:
detector: AnomalyDetector instance
X_normal_val: Validation normal data
X_anomaly_val: Validation anomaly data
metric: 'f1', 'sensitivity', 'specificity', or 'precision'
Returns:
optimal_threshold: Best threshold value
metrics_dict: Performance metrics at optimal threshold
"""
from sklearn.metrics import f1_score, precision_score, recall_score
errors_normal = detector.get_reconstruction_error(X_normal_val)
errors_anomaly = detector.get_reconstruction_error(X_anomaly_val)
all_errors = np.concatenate([errors_normal, errors_anomaly])
y_true = np.concatenate([np.zeros(len(X_normal_val)), np.ones(len(X_anomaly_val))])
thresholds = np.percentile(all_errors, np.linspace(1, 99, 99))
best_score = -1
best_threshold = None
best_metrics = None
for threshold in thresholds:
y_pred = (all_errors > threshold).astype(int)
if metric == 'f1':
score = f1_score(y_true, y_pred, zero_division=0)
elif metric == 'sensitivity':
score = recall_score(y_true, y_pred, zero_division=0)
elif metric == 'specificity':
tn = np.sum((y_pred == 0) & (y_true == 0))
fp = np.sum((y_pred == 1) & (y_true == 0))
score = tn / (tn + fp) if (tn + fp) > 0 else 0
elif metric == 'precision':
score = precision_score(y_true, y_pred, zero_division=0)
if score > best_score:
best_score = score
best_threshold = threshold
best_metrics = {
'f1': f1_score(y_true, y_pred, zero_division=0),
'sensitivity': recall_score(y_true, y_pred, zero_division=0),
'precision': precision_score(y_true, y_pred, zero_division=0),
}
detector.threshold = best_threshold
print(f"Optimal threshold ({metric}): {best_threshold:.6f}")
print(f"Metrics: {best_metrics}")
return best_threshold, best_metrics
# Save and load model
def save_detector(detector, filepath):
"""Save detector to disk"""
import pickle
state = {
'model_state': detector.model.state_dict(),
'scaler': detector.scaler,
'threshold': detector.threshold,
'training_errors': detector.training_errors,
}
torch.save(state, filepath)
print(f"Detector saved to {filepath}")
def load_detector(filepath, input_dim, hidden_dims=[64, 32, 16]):
"""Load detector from disk"""
state = torch.load(filepath)
detector = AnomalyDetector(input_dim, hidden_dims)
detector.model.load_state_dict(state['model_state'])
detector.scaler = state['scaler']
detector.threshold = state['threshold']
detector.training_errors = state['training_errors']
print(f"Detector loaded from {filepath}")
return detector
4. Complete Example with Real-World Scenario
def example_credit_card_fraud():
"""
Example: Detect credit card fraud
Simulates transaction features
"""
print("\n" + "=" * 80)
print("EXAMPLE: CREDIT CARD FRAUD DETECTION")
print("=" * 80)
# Generate synthetic credit card transaction data
np.random.seed(42)
# Normal transactions
n_normal = 5000
normal_transactions = np.random.randn(n_normal, 15)
normal_transactions *= np.array([100, 50, 20, 10, 5, 1, 0.5, 0.2, 0.1,
0.05, 0.02, 0.01, 0.01, 0.01, 0.01])
# Fraudulent transactions (anomalies)
n_fraud = 200
fraud_transactions = np.random.randn(n_fraud, 15) * 3
fraud_transactions += np.array([300, 150, 50, 30, 10, 5, 2, 1, 0.5,
0.2, 0.1, 0.05, 0.02, 0.01, 0.01])
# Split data
split_idx = int(0.7 * n_normal)
X_train = normal_transactions[:split_idx]
X_normal_test = normal_transactions[split_idx:]
X_fraud_test = fraud_transactions
print(f"Training data: {X_train.shape}")
print(f"Normal test data: {X_normal_test.shape}")
print(f"Fraud test data: {X_fraud_test.shape}")
# Train detector
print("\nTraining detector...")
detector = AdvancedAnomalyDetector(input_dim=15, hidden_dims=[32, 16, 8])
history = detector.train(X_train, epochs=50, batch_size=64, lr=0.001, verbose=False)
# Set threshold
detector.set_threshold(percentile=99)
# Make predictions
y_pred_normal, _ = detector.predict(X_normal_test, return_scores=True)
y_pred_fraud, fraud_errors = detector.predict(X_fraud_test, return_scores=True)
print(f"\nNormal transactions flagged as fraud: {np.sum(y_pred_normal)}/{len(X_normal_test)} "
f"({100*np.sum(y_pred_normal)/len(X_normal_test):.2f}%)")
print(f"Fraud transactions detected: {np.sum(y_pred_fraud)}/{len(X_fraud_test)} "
f"({100*np.sum(y_pred_fraud)/len(X_fraud_test):.2f}%)")
# Get details of top frauds
print("\nTop 5 detected frauds:")
print(detector.get_anomaly_details(X_fraud_test, top_n=5))
def example_time_series_anomaly():
"""
Example: Detect anomalies in time series sensor data
"""
print("\n" + "=" * 80)
print("EXAMPLE: TIME SERIES SENSOR ANOMALY DETECTION")
print("=" * 80)
# Generate synthetic sensor data
np.random.seed(42)
n_timesteps = 3000
n_features = 10
# Normal sensor readings (periodic pattern)
t = np.arange(n_timesteps)
normal_data = []
for i in range(n_features):
normal_data.append(np.sin(2 * np.pi * t / 200 + i) + 0.1 * np.random.randn(n_timesteps))
normal_data = np.array(normal_data).T
# Add anomalies (spikes)
anomaly_indices = np.random.choice(1500, 200, replace=False)
anomaly_mask = np.isin(np.arange(n_timesteps), anomaly_indices)
for i in range(n_features):
normal_data[anomaly_mask, i] += 5 * np.random.randn(np.sum(anomaly_mask))
# Split
split_idx = 2000
X_train = normal_data[:split_idx]
X_test = normal_data[split_idx:]
print(f"Training data: {X_train.shape}")
print(f"Test data: {X_test.shape}")
print(f"Anomalies in test set: {np.sum(anomaly_mask[split_idx:])}")
# Train
print("\nTraining detector...")
detector = AnomalyDetector(input_dim=n_features, hidden_dims=[32, 16])
detector.train(X_train, epochs=100, batch_size=32, verbose=False)
detector.set_threshold(percentile=99)
# Evaluate
y_pred, errors = detector.predict(X_test, return_scores=True)
detected_anomalies = np.sum(y_pred)
true_anomalies = np.sum(anomaly_mask[split_idx:])
print(f"\nTrue anomalies in test set: {true_anomalies}")
print(f"Detected anomalies: {detected_anomalies}")
print(f"Detection rate: {100*detected_anomalies/max(true_anomalies, 1):.2f}%")
if __name__ == "__main__":
# Run examples
example_credit_card_fraud()
example_time_series_anomaly()
Key Features
✅ Core Functionality:
- Autoencoder trained on normal data only
- Reconstruction error-based anomaly detection
- Automatic threshold setting at 99th percentile
- Normalizes input data
✅ Advanced Features:
- Adaptive threshold updating
- Anomaly details and explanations
- Optimal threshold finding
- Batch predictions with confidence scores
✅ Visualization:
- Training history plots
- Reconstruction error distributions
- ROC curves
- Latent space visualization
- Feature-wise reconstruction comparison
✅ Model Management:
- Save/load trained detectors
- Training/validation split
- Batch processing
This implementation provides a production-ready anomaly detection system!