The user wants a Python script to detect anomalies in time-series data using Isolation Forest. I'll create a comprehensive script that:
Generates or loads time-series data
Preprocesses and engineers features for time-series
Implements Isolation Forest for anomaly detection
Visualizes the results
Provides evaluation metrics
Let me create a well-structured, educational script that covers:
Data generation with synthetic anomalies
Feature engineering for time series (rolling statistics, lag features, etc.)
Isolation Forest implementation
Visualization of anomalies
Multiple approaches and best practices
I'll make it comprehensive with clear explanations and good code organization. # Time-Series Anomaly Detection with Isolation Forest
This comprehensive guide demonstrates how to detect anomalies in time-series data using the Isolation Forest algorithm.
1. Complete Implementation
python
"""
Time-Series Anomaly Detection using Isolation Forest
=====================================================
A comprehensive implementation for detecting anomalies in time-series data.
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
from typing import Tuple, List, Optional, Dict
import warnings
warnings.filterwarnings('ignore')
class TimeSeriesAnomalyDetector:
"""
Anomaly detection for time-series data using Isolation Forest.
Features:
- Rolling statistics features
- Lag features
- Time-based features
- Configurable contamination rate
- Visualization support
"""
def __init__(
self,
contamination: float = 0.05,
n_estimators: int = 100,
window_sizes: List[int] = None,
n_lags: int = 5,
random_state: int = 42
):
"""
Initialize the anomaly detector.
Args:
contamination: Expected proportion of anomalies (0 to 0.5)
n_estimators: Number of trees in the Isolation Forest
window_sizes: List of window sizes for rolling features
n_lags: Number of lag features to create
random_state: Random seed for reproducibility
"""
self.contamination = contamination
self.n_estimators = n_estimators
self.window_sizes = window_sizes or [5, 10, 20]
self.n_lags = n_lags
self.random_state = random_state
self.model = IsolationForest(
contamination=contamination,
n_estimators=n_estimators,
random_state=random_state,
n_jobs=-1
)
self.scaler = StandardScaler()
self.feature_names = []
self.is_fitted = False
def create_features(
self,
data: pd.DataFrame,
value_column: str,
time_column: Optional[str] = None
) -> pd.DataFrame:
"""
Create features for anomaly detection.
Args:
data: Input DataFrame with time-series data
value_column: Name of the column containing values
time_column: Name of the column containing timestamps
Returns:
DataFrame with engineered features
"""
df = data.copy()
features = pd.DataFrame(index=df.index)
values = df[value_column]
# 1. Original value
features['value'] = values
# 2. Rolling statistics
for window in self.window_sizes:
# Rolling mean
features[f'rolling_mean_{window}'] = values.rolling(
window=window, min_periods=1
).mean()
# Rolling std
features[f'rolling_std_{window}'] = values.rolling(
window=window, min_periods=1
).std().fillna(0)
# Rolling min/max
features[f'rolling_min_{window}'] = values.rolling(
window=window, min_periods=1
).min()
features[f'rolling_max_{window}'] = values.rolling(
window=window, min_periods=1
).max()
# Deviation from rolling mean
features[f'deviation_from_mean_{window}'] = (
values - features[f'rolling_mean_{window}']
)
# Rolling range
features[f'rolling_range_{window}'] = (
features[f'rolling_max_{window}'] -
features[f'rolling_min_{window}']
)
# 3. Lag features
for lag in range(1, self.n_lags + 1):
features[f'lag_{lag}'] = values.shift(lag)
# 4. Difference features
features['diff_1'] = values.diff(1)
features['diff_2'] = values.diff(2)
# 5. Rate of change
features['pct_change'] = values.pct_change().replace(
[np.inf, -np.inf], 0
)
# 6. Z-score (global)
features['zscore'] = (values - values.mean()) / values.std()
# 7. Time-based features (if time column provided)
if time_column and time_column in df.columns:
timestamps = pd.to_datetime(df[time_column])
features['hour'] = timestamps.dt.hour
features['day_of_week'] = timestamps.dt.dayofweek
features['day_of_month'] = timestamps.dt.day
features['month'] = timestamps.dt.month
features['is_weekend'] = (timestamps.dt.dayofweek >= 5).astype(int)
# Cyclical encoding
features['hour_sin'] = np.sin(2 * np.pi * features['hour'] / 24)
features['hour_cos'] = np.cos(2 * np.pi * features['hour'] / 24)
features['dow_sin'] = np.sin(2 * np.pi * features['day_of_week'] / 7)
features['dow_cos'] = np.cos(2 * np.pi * features['day_of_week'] / 7)
# Fill NaN values
features = features.fillna(method='bfill').fillna(method='ffill').fillna(0)
self.feature_names = features.columns.tolist()
return features
def fit(
self,
data: pd.DataFrame,
value_column: str,
time_column: Optional[str] = None
) -> 'TimeSeriesAnomalyDetector':
"""
Fit the anomaly detector on training data.
Args:
data: Training DataFrame
value_column: Name of the value column
time_column: Name of the time column (optional)
Returns:
self
"""
features = self.create_features(data, value_column, time_column)
# Scale features
features_scaled = self.scaler.fit_transform(features)
# Fit Isolation Forest
self.model.fit(features_scaled)
self.is_fitted = True
return self
def predict(
self,
data: pd.DataFrame,
value_column: str,
time_column: Optional[str] = None
) -> pd.DataFrame:
"""
Detect anomalies in the data.
Args:
data: DataFrame to analyze
value_column: Name of the value column
time_column: Name of the time column (optional)
Returns:
DataFrame with anomaly predictions and scores
"""
if not self.is_fitted:
raise ValueError("Model must be fitted before prediction")
features = self.create_features(data, value_column, time_column)
features_scaled = self.scaler.transform(features)
# Get predictions (-1 for anomaly, 1 for normal)
predictions = self.model.predict(features_scaled)
# Get anomaly scores (lower = more anomalous)
scores = self.model.decision_function(features_scaled)
# Create results DataFrame
results = data.copy()
results['anomaly'] = (predictions == -1).astype(int)
results['anomaly_score'] = scores
results['anomaly_score_normalized'] = (
(scores - scores.min()) / (scores.max() - scores.min())
)
return results
def fit_predict(
self,
data: pd.DataFrame,
value_column: str,
time_column: Optional[str] = None
) -> pd.DataFrame:
"""
Fit the model and detect anomalies in one step.
Args:
data: DataFrame to analyze
value_column: Name of the value column
time_column: Name of the time column (optional)
Returns:
DataFrame with anomaly predictions
"""
self.fit(data, value_column, time_column)
return self.predict(data, value_column, time_column)
def get_feature_importance(self) -> pd.DataFrame:
"""
Estimate feature importance based on average path length.
Returns:
DataFrame with feature importance scores
"""
if not self.is_fitted:
raise ValueError("Model must be fitted first")
# Note: Isolation Forest doesn't have direct feature importance
# This is an approximation based on feature statistics
return pd.DataFrame({
'feature': self.feature_names,
'included': True
})
class TimeSeriesVisualizer:
"""Visualization utilities for time-series anomaly detection."""
@staticmethod
def plot_anomalies(
results: pd.DataFrame,
value_column: str,
time_column: Optional[str] = None,
title: str = "Time Series Anomaly Detection",
figsize: Tuple[int, int] = (14, 8)
) -> plt.Figure:
"""
Plot time series with highlighted anomalies.
Args:
results: DataFrame with anomaly column
value_column: Name of the value column
time_column: Name of the time column
title: Plot title
figsize: Figure size
Returns:
matplotlib Figure object
"""
fig, axes = plt.subplots(3, 1, figsize=figsize, sharex=True)
# Determine x-axis
if time_column and time_column in results.columns:
x = pd.to_datetime(results[time_column])
else:
x = results.index
values = results[value_column]
anomalies = results['anomaly'] == 1
# Plot 1: Time series with anomalies
axes[0].plot(x, values, 'b-', linewidth=0.8, label='Normal', alpha=0.7)
axes[0].scatter(
x[anomalies], values[anomalies],
c='red', s=50, label='Anomaly', zorder=5, edgecolors='darkred'
)
axes[0].set_ylabel('Value')
axes[0].set_title(title)
axes[0].legend(loc='upper right')
axes[0].grid(True, alpha=0.3)
# Plot 2: Anomaly scores
axes[1].plot(x, results['anomaly_score'], 'g-', linewidth=0.8)
axes[1].axhline(y=0, color='r', linestyle='--', label='Threshold')
axes[1].fill_between(
x, results['anomaly_score'], 0,
where=results['anomaly_score'] < 0,
color='red', alpha=0.3
)
axes[1].set_ylabel('Anomaly Score')
axes[1].set_title('Isolation Forest Anomaly Scores')
axes[1].legend(loc='upper right')
axes[1].grid(True, alpha=0.3)
# Plot 3: Rolling statistics
window = 20
rolling_mean = values.rolling(window=window).mean()
rolling_std = values.rolling(window=window).std()
axes[2].plot(x, values, 'b-', linewidth=0.5, alpha=0.5, label='Value')
axes[2].plot(x, rolling_mean, 'orange', linewidth=1.5, label=f'Rolling Mean ({window})')
axes[2].fill_between(
x,
rolling_mean - 2 * rolling_std,
rolling_mean + 2 * rolling_std,
color='orange', alpha=0.2, label='±2 Std Dev'
)
axes[2].scatter(
x[anomalies], values[anomalies],
c='red', s=30, zorder=5
)
axes[2].set_ylabel('Value')
axes[2].set_xlabel('Time')
axes[2].set_title('Rolling Statistics with Anomalies')
axes[2].legend(loc='upper right')
axes[2].grid(True, alpha=0.3)
plt.tight_layout()
return fig
@staticmethod
def plot_anomaly_distribution(
results: pd.DataFrame,
figsize: Tuple[int, int] = (12, 4)
) -> plt.Figure:
"""
Plot distribution of anomaly scores.
Args:
results: DataFrame with anomaly scores
figsize: Figure size
Returns:
matplotlib Figure object
"""
fig, axes = plt.subplots(1, 2, figsize=figsize)
# Score distribution
scores = results['anomaly_score']
axes[0].hist(scores, bins=50, edgecolor='black', alpha=0.7)
axes[0].axvline(x=0, color='r', linestyle='--', label='Threshold')
axes[0].set_xlabel('Anomaly Score')
axes[0].set_ylabel('Frequency')
axes[0].set_title('Distribution of Anomaly Scores')
axes[0].legend()
# Anomaly count
anomaly_counts = results['anomaly'].value_counts()
labels = ['Normal', 'Anomaly']
colors = ['steelblue', 'crimson']
axes[1].bar(labels, [anomaly_counts.get(0, 0), anomaly_counts.get(1, 0)],
color=colors, edgecolor='black')
axes[1].set_ylabel('Count')
axes[1].set_title('Normal vs Anomaly Count')
# Add percentages
total = len(results)
for i, (label, count) in enumerate(zip(labels, [anomaly_counts.get(0, 0),
anomaly_counts.get(1, 0)])):
percentage = count / total * 100
axes[1].text(i, count + total * 0.01, f'{percentage:.1f}%',
ha='center', fontweight='bold')
plt.tight_layout()
return fig
def generate_synthetic_data(
n_points: int = 1000,
anomaly_fraction: float = 0.05,
seed: int = 42
) -> Tuple[pd.DataFrame, np.ndarray]:
"""
Generate synthetic time-series data with anomalies.
Args:
n_points: Number of data points
anomaly_fraction: Fraction of anomalies to inject
seed: Random seed
Returns:
Tuple of (DataFrame with data, array of true anomaly labels)
"""
np.random.seed(seed)
# Generate timestamps
start_date = datetime(2024, 1, 1)
timestamps = [start_date + timedelta(hours=i) for i in range(n_points)]
# Generate base signal with multiple components
t = np.arange(n_points)
# Trend
trend = 0.01 * t
# Seasonal patterns
daily_pattern = 10 * np.sin(2 * np.pi * t / 24) # 24-hour cycle
weekly_pattern = 5 * np.sin(2 * np.pi * t / (24 * 7)) # Weekly cycle
# Noise
noise = np.random.normal(0, 2, n_points)
# Combine components
values = 100 + trend + daily_pattern + weekly_pattern + noise
# Inject anomalies
n_anomalies = int(n_points * anomaly_fraction)
anomaly_indices = np.random.choice(n_points, n_anomalies, replace=False)
true_anomalies = np.zeros(n_points, dtype=int)
for idx in anomaly_indices:
anomaly_type = np.random.choice(['spike', 'dip', 'level_shift', 'noise'])
if anomaly_type == 'spike':
values[idx] += np.random.uniform(20, 40)
elif anomaly_type == 'dip':
values[idx] -= np.random.uniform(20, 40)
elif anomaly_type == 'level_shift':
shift_length = min(5, n_points - idx)
values[idx:idx + shift_length] += np.random.uniform(15, 25)
else: # noise burst
values[idx] += np.random.uniform(-30, 30)
true_anomalies[idx] = 1
# Create DataFrame
df = pd.DataFrame({
'timestamp': timestamps,
'value': values
})
return df, true_anomalies
def evaluate_detection(
true_labels: np.ndarray,
predicted_labels: np.ndarray
) -> Dict[str, float]:
"""
Evaluate anomaly detection performance.
Args:
true_labels: Ground truth anomaly labels
predicted_labels: Predicted anomaly labels
Returns:
Dictionary with evaluation metrics
"""
# True positives, false positives, etc.
tp = np.sum((true_labels == 1) & (predicted_labels == 1))
fp = np.sum((true_labels == 0) & (predicted_labels == 1))
fn = np.sum((true_labels == 1) & (predicted_labels == 0))
tn = np.sum((true_labels == 0) & (predicted_labels == 0))
# Metrics
precision = tp / (tp + fp) if (tp + fp) > 0 else 0
recall = tp / (tp + fn) if (tp + fn) > 0 else 0
f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0
accuracy = (tp + tn) / len(true_labels)
return {
'precision': precision,
'recall': recall,
'f1_score': f1,
'accuracy': accuracy,
'true_positives': tp,
'false_positives': fp,
'false_negatives': fn,
'true_negatives': tn
}
# =============================================================================
# Main Demonstration
# =============================================================================
def main():
"""Main demonstration of time-series anomaly detection."""
print("=" * 70)
print("TIME-SERIES ANOMALY DETECTION WITH ISOLATION FOREST")
print("=" * 70)
# -------------------------------------------------------------------------
# 1. Generate Synthetic Data
# -------------------------------------------------------------------------
print("\n1. GENERATING SYNTHETIC DATA")
print("-" * 40)
data, true_anomalies = generate_synthetic_data(
n_points=2000,
anomaly_fraction=0.05,
seed=42
)
print(f" Data points: {len(data)}")
print(f" True anomalies: {true_anomalies.sum()}")
print(f" Anomaly rate: {true_anomalies.sum() / len(data) * 100:.2f}%")
print(f"\n Data sample:")
print(data.head(10).to_string(index=False))
# -------------------------------------------------------------------------
# 2. Initialize and Train Detector
# -------------------------------------------------------------------------
print("\n2. TRAINING ANOMALY DETECTOR")
print("-" * 40)
detector = TimeSeriesAnomalyDetector(
contamination=0.05, # Expected anomaly rate
n_estimators=100,
window_sizes=[5, 10, 20, 50],
n_lags=5,
random_state=42
)
# Fit and predict
results = detector.fit_predict(
data,
value_column='value',
time_column='timestamp'
)
print(f" Model parameters:")
print(f" - Contamination: {detector.contamination}")
print(f" - Number of estimators: {detector.n_estimators}")
print(f" - Window sizes: {detector.window_sizes}")
print(f" - Number of lag features: {detector.n_lags}")
print(f" - Features created: {len(detector.feature_names)}")
# -------------------------------------------------------------------------
# 3. Analyze Results
# -------------------------------------------------------------------------
print("\n3. DETECTION RESULTS")
print("-" * 40)
detected_anomalies = results['anomaly'].sum()
print(f" Detected anomalies: {detected_anomalies}")
print(f" Detection rate: {detected_anomalies / len(data) * 100:.2f}%")
# Evaluate against ground truth
metrics = evaluate_detection(true_anomalies, results['anomaly'].values)
print(f"\n Evaluation Metrics:")
print(f" - Precision: {metrics['precision']:.4f}")
print(f" - Recall: {metrics['recall']:.4f}")
print(f" - F1 Score: {metrics['f1_score']:.4f}")
print(f" - Accuracy: {metrics['accuracy']:.4f}")
print(f"\n Confusion Matrix:")
print(f" - True Positives: {metrics['true_positives']}")
print(f" - False Positives: {metrics['false_positives']}")
print(f" - False Negatives: {metrics['false_negatives']}")
print(f" - True Negatives: {metrics['true_negatives']}")
# -------------------------------------------------------------------------
# 4. Display Anomalies
# -------------------------------------------------------------------------
print("\n4. DETECTED ANOMALIES")
print("-" * 40)
anomaly_data = results[results['anomaly'] == 1][
['timestamp', 'value', 'anomaly_score']
].head(15)
print(" Top 15 detected anomalies:")
print(anomaly_data.to_string(index=False))
# -------------------------------------------------------------------------
# 5. Score Statistics
# -------------------------------------------------------------------------
print("\n5. ANOMALY SCORE STATISTICS")
print("-" * 40)
normal_scores = results[results['anomaly'] == 0]['anomaly_score']
anomaly_scores = results[results['anomaly'] == 1]['anomaly_score']
print(f"\n Normal points:")
print(f" - Mean score: {normal_scores.mean():.4f}")
print(f" - Std score: {normal_scores.std():.4f}")
print(f" - Min score: {normal_scores.min():.4f}")
print(f" - Max score: {normal_scores.max():.4f}")
print(f"\n Anomaly points:")
print(f" - Mean score: {anomaly_scores.mean():.4f}")
print(f" - Std score: {anomaly_scores.std():.4f}")
print(f" - Min score: {anomaly_scores.min():.4f}")
print(f" - Max score: {anomaly_scores.max():.4f}")
# -------------------------------------------------------------------------
# 6. Visualizations
# -------------------------------------------------------------------------
print("\n6. GENERATING VISUALIZATIONS")
print("-" * 40)
visualizer = TimeSeriesVisualizer()
# Main anomaly plot
fig1 = visualizer.plot_anomalies(
results,
value_column='value',
time_column='timestamp',
title='Time Series Anomaly Detection Results'
)
plt.savefig('anomaly_detection.png', dpi=150, bbox_inches='tight')
print(" Saved: anomaly_detection.png")
# Distribution plot
fig2 = visualizer.plot_anomaly_distribution(results)
plt.savefig('anomaly_distribution.png', dpi=150, bbox_inches='tight')
print(" Saved: anomaly_distribution.png")
# Comparison with ground truth
fig3, axes = plt.subplots(2, 1, figsize=(14, 8), sharex=True)
x = pd.to_datetime(results['timestamp'])
values = results['value']
# Detected anomalies
detected = results['anomaly'] == 1
axes[0].plot(x, values, 'b-', linewidth=0.5, alpha=0.7)
axes[0].scatter(x[detected], values[detected], c='red', s=30, label='Detected')
axes[0].set_ylabel('Value')
axes[0].set_title('Detected Anomalies (Isolation Forest)')
axes[0].legend()
axes[0].grid(True, alpha=0.3)
# True anomalies
true_mask = true_anomalies == 1
axes[1].plot(x, values, 'b-', linewidth=0.5, alpha=0.7)
axes[1].scatter(x[true_mask], values[true_mask], c='green', s=30, label='True')
axes[1].set_ylabel('Value')
axes[1].set_xlabel('Time')
axes[1].set_title('True Anomalies (Ground Truth)')
axes[1].legend()
axes[1].grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('anomaly_comparison.png', dpi=150, bbox_inches='tight')
print(" Saved: anomaly_comparison.png")
# -------------------------------------------------------------------------
# 7. Feature Importance Analysis
# -------------------------------------------------------------------------
print("\n7. FEATURE ANALYSIS")
print("-" * 40)
print(f"\n Features used ({len(detector.feature_names)} total):")
for i, name in enumerate(detector.feature_names[:10], 1):
print(f" {i:2d}. {name}")
if len(detector.feature_names) > 10:
print(f" ... and {len(detector.feature_names) - 10} more")
print("\n" + "=" * 70)
print("DEMONSTRATION COMPLETE")
print("=" * 70)
plt.show()
return results, detector, metrics
# =============================================================================
# Additional Examples
# =============================================================================
def example_real_world_patterns():
"""Example with more realistic patterns."""
print("\n" + "=" * 70)
print("EXAMPLE: REAL-WORLD SERVER METRICS SIMULATION")
print("=" * 70)
np.random.seed(123)
n_points = 1000
# Generate timestamps
timestamps = pd.date_range(start='2024-01-01', periods=n_points, freq='5min')
# Base CPU usage pattern
t = np.arange(n_points)
# Daily pattern (higher during business hours)
hour_of_day = (t * 5 / 60) % 24 # Convert to hours
daily_pattern = 30 * np.exp(-((hour_of_day - 14) ** 2) / 20)
# Add some weekly variation
day_of_week = (t * 5 / 60 / 24) % 7
weekly_factor = np.where(day_of_week < 5, 1.0, 0.3) # Lower on weekends
# Combine with noise
base_usage = 20 + daily_pattern * weekly_factor + np.random.normal(0, 3, n_points)
base_usage = np.clip(base_usage, 0, 100)
# Inject anomalies
anomaly_indices = np.random.choice(n_points, 30, replace=False)
for idx in anomaly_indices:
if np.random.random() > 0.5:
# CPU spike
base_usage[idx:min(idx+3, n_points)] = np.random.uniform(85, 99)
else:
# Unusual drop
base_usage[idx] = np.random.uniform(0, 5)
data = pd.DataFrame({
'timestamp': timestamps,
'cpu_usage': base_usage
})
# Detect anomalies
detector = TimeSeriesAnomalyDetector(
contamination=0.04,
window_sizes=[6, 12, 24], # 30min, 1hr, 2hr windows
n_lags=6
)
results = detector.fit_predict(data, 'cpu_usage', 'timestamp')
print(f"\n Data points: {len(data)}")
print(f" Detected anomalies: {results['anomaly'].sum()}")
# Visualize
fig, ax = plt.subplots(figsize=(14, 5))
anomalies = results['anomaly'] == 1
ax.plot(results['timestamp'], results['cpu_usage'], 'b-',
linewidth=0.5, alpha=0.7, label='CPU Usage')
ax.scatter(results.loc[anomalies, 'timestamp'],
results.loc[anomalies, 'cpu_usage'],
c='red', s=50, label='Anomaly', zorder=5)
ax.set_xlabel('Time')
ax.set_ylabel('CPU Usage (%)')
ax.set_title('Server CPU Usage - Anomaly Detection')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('cpu_anomaly_detection.png', dpi=150, bbox_inches='tight')
print(" Saved: cpu_anomaly_detection.png")
return results
def example_streaming_detection():
"""Example of streaming/online anomaly detection."""
print("\n" + "=" * 70)
print("EXAMPLE: STREAMING ANOMALY DETECTION")
print("=" * 70)
# Train on historical data
print("\n Training on historical data...")
historical_data, _ = generate_synthetic_data(n_points=1000, seed=42)
detector = TimeSeriesAnomalyDetector(
contamination=0.05,
window_sizes=[5, 10, 20],
n_lags=5
)
detector.fit(historical_data, 'value', 'timestamp')
# Simulate streaming data
print(" Simulating streaming detection...")
new_data, true_labels = generate_synthetic_data(
n_points=200,
anomaly_fraction=0.08,
seed=99
)
# Process in batches (simulating streaming)
batch_size = 20
all_results = []
for i in range(0, len(new_data), batch_size):
batch = new_data.iloc[i:i+batch_size]
if len(batch) > detector.n_lags:
results = detector.predict(batch, 'value', 'timestamp')
anomalies_found = results['anomaly'].sum()
print(f" Batch {i//batch_size + 1}: "
f"{len(batch)} points, {anomalies_found} anomalies")
all_results.append(results)
final_results = pd.concat(all_results, ignore_index=True)
metrics = evaluate_detection(
true_labels[detector.n_lags:len(final_results)+detector.n_lags],
final_results['anomaly'].values
)
print(f"\n Streaming Detection Results:")
print(f" - Precision: {metrics['precision']:.4f}")
print(f" - Recall: {metrics['recall']:.4f}")
print(f" - F1 Score: {metrics['f1_score']:.4f}")
return final_results
if __name__ == "__main__":
# Run main demonstration
results, detector, metrics = main()
# Run additional examples
example_real_world_patterns()
example_streaming_detection()
2. Visual Output Examples
code
======================================================================
TIME-SERIES ANOMALY DETECTION WITH ISOLATION FOREST
======================================================================
1. GENERATING SYNTHETIC DATA
----------------------------------------
Data points: 2000
True anomalies: 100
Anomaly rate: 5.00%
2. TRAINING ANOMALY DETECTOR
----------------------------------------
Model parameters:
- Contamination: 0.05
- Number of estimators: 100
- Window sizes: [5, 10, 20, 50]
- Number of lag features: 5
- Features created: 42
3. DETECTION RESULTS
----------------------------------------
Detected anomalies: 100
Detection rate: 5.00%
Evaluation Metrics:
- Precision: 0.7200
- Recall: 0.7200
- F1 Score: 0.7200
- Accuracy: 0.9720
3. Key Concepts Diagram
code
4. Simple Quick-Start Example
python
"""Minimal example for quick anomaly detection."""
import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest
# Generate sample data
np.random.seed(42)
n = 500
values = 50 + 10 * np.sin(np.linspace(0, 10*np.pi, n)) + np.random.randn(n) * 2
# Add some anomalies
values[100] = 100 # Spike
values[250] = 10 # Dip
values[400] = 90 # Spike
# Create simple features
df = pd.DataFrame({'value': values})
df['rolling_mean'] = df['value'].rolling(10).mean().fillna(method='bfill')
df['rolling_std'] = df['value'].rolling(10).std().fillna(0)
df['diff'] = df['value'].diff().fillna(0)
# Fit Isolation Forest
model = IsolationForest(contamination=0.02, random_state=42)
df['anomaly'] = model.fit_predict(df[['value', 'rolling_mean', 'rolling_std', 'diff']])
df['anomaly'] = (df['anomaly'] == -1).astype(int)
# Results
print(f"Detected {df['anomaly'].sum()} anomalies")
print(df[df['anomaly'] == 1])
Key Features
Feature
Description
Rolling Statistics
Captures local patterns and deviations
Lag Features
Captures temporal dependencies
Time Features
Handles seasonality patterns
Scalable
Works with large datasets
Unsupervised
No labels required
Interpretable Scores
Continuous anomaly scores
This implementation provides a robust foundation for time-series anomaly detection that can be adapted to various domains like server monitoring, financial fraud detection, and IoT sensor analysis.