import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest
# ==========================================
# 1. Generate Synthetic Time-Series Data
# ==========================================
def generate_data(n=200):
np.random.seed(42)
# Create a time range
time_steps = pd.date_range(start='2023-01-01', periods=n, freq='D')
# Generate a sine wave with some noise (Seasonality + Noise)
values = np.sin(np.linspace(0, 20, n)) + np.random.normal(scale=0.2, size=n)
# Create DataFrame
df = pd.DataFrame({'timestamp': time_steps, 'value': values})
# Inject artificial anomalies (Spikes)
df.loc[40, 'value'] = 3.5 # High outlier
df.loc[150, 'value'] = -3.0 # Low outlier
df.loc[160:163, 'value'] = 2.5 # Cluster of anomalies
return df.set_index('timestamp')
# ==========================================
# 2. Method A: Statistical (Rolling Z-Score)
# ==========================================
def detect_anomalies_stats(df, window=10, sigma=3.0):
"""
Flags points that deviate 'sigma' standard deviations
from the rolling mean.
"""
# Calculate rolling statistics
rolling_mean = df['value'].rolling(window=window).mean()
rolling_std = df['value'].rolling(window=window).std()
# Calculate Z-Score
# Note: We fill NaN created by rolling window with 0 to avoid errors
df['z_score'] = (df['value'] - rolling_mean) / rolling_std
# Flag anomalies
df['anomaly_stat'] = df['z_score'].apply(
lambda x: x > sigma or x < -sigma
)
return df
# ==========================================
# 3. Method B: Machine Learning (Isolation Forest)
# ==========================================
def detect_anomalies_ml(df, contamination=0.05):
"""
Uses Isolation Forest to detect outliers.
"""
# Prepare data (sklearn expects 2D array)
data = df[['value']].values
# Initialize model
# contamination: expected proportion of outliers in the dataset
model = IsolationForest(contamination=contamination, random_state=42)
# Fit and predict (-1 is anomaly, 1 is normal)
df['if_pred'] = model.fit_predict(data)
# Convert to boolean (True if anomaly)
df['anomaly_ml'] = df['if_pred'] == -1
return df
# ==========================================
# 4. Main Execution & Visualization
# ==========================================
if __name__ == "__main__":
# Generate Data
df = generate_data()
# Apply Detection Methods
df = detect_anomalies_stats(df, window=7, sigma=2.5)
df = detect_anomalies_ml(df, contamination=0.04)
# Plotting
fig, ax = plt.subplots(2, 1, figsize=(12, 10), sharex=True)
# Plot 1: Statistical Method
ax[0].plot(df.index, df['value'], label='Data', color='blue', alpha=0.6)
# Highlight Statistical Anomalies
anomalies_stat = df[df['anomaly_stat']]
ax[0].scatter(anomalies_stat.index, anomalies_stat['value'], color='red', label='Anomaly', zorder=5)
ax[0].set_title('Method 1: Rolling Z-Score Detection')
ax[0].legend()
ax[0].grid(True, linestyle='--', alpha=0.6)
# Plot 2: Machine Learning Method
ax[1].plot(df.index, df['value'], label='Data', color='green', alpha=0.6)
# Highlight ML Anomalies
anomalies_ml = df[df['anomaly_ml']]
ax[1].scatter(anomalies_ml.index, anomalies_ml['value'], color='red', label='Anomaly', zorder=5)
ax[1].set_title('Method 2: Isolation Forest (Machine Learning)')
ax[1].legend()
ax[1].grid(True, linestyle='--', alpha=0.6)
plt.show()
# Print identified anomalies
print("Statistical Method found:", df['anomaly_stat'].sum(), "anomalies")
print("ML Method found:", df['anomaly_ml'].sum(), "anomalies")