class StreamingAnomalyDetector:
"""
Handles streaming data with concept drift and online learning.
"""
def __init__(self, n_trees: int = 50, window_size: int = 1000,
check_interval: int = 100, contamination: float = 0.05):
"""
Args:
n_trees: Number of trees per model
window_size: Size of sliding window for retraining
check_interval: Interval for model retraining
contamination: Expected anomaly rate
"""
self.n_trees = n_trees
self.window_size = window_size
self.check_interval = check_interval
self.contamination = contamination
self.model = None
self.data_buffer = []
self.predictions_history = []
self.scores_history = []
self.timestamps = []
self.n_samples_seen = 0
def process_stream(self, X: np.ndarray, timestamps: np.ndarray = None):
"""
Process streaming data points one by one or in batches.
"""
if timestamps is None:
timestamps = np.arange(len(X))
for i, (sample, timestamp) in enumerate(zip(X, timestamps)):
self.process_sample(sample.reshape(1, -1), timestamp)
def process_sample(self, sample: np.ndarray, timestamp: float = None):
"""Process a single sample"""
if timestamp is None:
timestamp = self.n_samples_seen
self.n_samples_seen += 1
self.data_buffer.append(sample[0])
# Retrain model periodically
if self.n_samples_seen % self.check_interval == 0:
self._retrain_model()
# Get prediction
if self.model is not None:
score = self.model.anomaly_score(sample)[0]
prediction = self.model.predict_with_threshold(
sample,
self.model.threshold
)[0]
else:
score = 0
prediction = 1 # Normal by default
self.scores_history.append(score)
self.predictions_history.append(prediction)
self.timestamps.append(timestamp)
# Keep only recent data in buffer
if len(self.data_buffer) > self.window_size:
self.data_buffer.pop(0)
def _retrain_model(self):
"""Retrain model with recent data"""
if len(self.data_buffer) < 100:
return
X = np.array(self.data_buffer[-self.window_size:])
self.model = IsolationForest(
n_trees=self.n_trees,
contamination=self.contamination,
max_depth=10
)
self.model.fit(X)
def get_stream_statistics(self) -> Dict:
"""Get statistics about the stream"""
if len(self.predictions_history) == 0:
return {}
predictions = np.array(self.predictions_history)
scores = np.array(self.scores_history)
return {
'total_samples': self.n_samples_seen,
'n_anomalies': (predictions == -1).sum(),
'anomaly_rate': (predictions == -1).sum() / len(predictions),
'avg_score': scores.mean(),
'score_std': scores.std(),
'max_score': scores.max(),
'min_score': scores.min()
}
def detect_recent_anomalies(self, lookback: int = 100) -> List[int]:
"""Get indices of recent anomalies"""
if len(self.predictions_history) < lookback:
lookback = len(self.predictions_history)
recent_predictions = self.predictions_history[-lookback:]
recent_indices = np.where(
np.array(recent_predictions) == -1
)[0]
# Convert to absolute indices
offset = len(self.predictions_history) - lookback
return (recent_indices + offset).tolist()
def generate_synthetic_data(n_normal: int = 1000,
n_anomalies: int = 50) -> Tuple:
"""Generate synthetic dataset with known anomalies"""
np.random.seed(42)
# Normal data: 2D Gaussian clusters
normal_data = np.vstack([
np.random.normal(loc=[0, 0], scale=1, size=(n_normal//2, 2)),
np.random.normal(loc=[5, 5], scale=1, size=(n_normal//2, 2))
])
# Anomalies: random points far from clusters
anomalies = np.random.uniform(
low=-10, high=15, size=(n_anomalies, 2)
)
X = np.vstack([normal_data, anomalies])
y = np.hstack([np.ones(n_normal), -np.ones(n_anomalies)])
# Shuffle
indices = np.random.permutation(len(X))
return X[indices], y[indices]
def generate_stream_data(n_samples: int = 5000) -> Tuple:
"""Generate streaming data with concept drift"""
data = []
labels = []
# Phase 1: Normal data around [0, 0]
phase1_size = n_samples // 3
data.append(np.random.normal(loc=[0, 0], scale=1, size=(phase1_size, 2)))
labels.append(np.ones(phase1_size))
# Add some anomalies
anomalies1 = np.random.uniform(low=-8, high=8, size=(50, 2))
data.append(anomalies1)
labels.append(-np.ones(50))
# Phase 2: Concept drift - normal data shifts to [5, 5]
phase2_size = n_samples // 3
data.append(np.random.normal(loc=[5, 5], scale=1, size=(phase2_size, 2)))
labels.append(np.ones(phase2_size))
# Add anomalies in new region
anomalies2 = np.random.uniform(low=[3, 3], high=[7, 7], size=(50, 2))
anomalies2 += np.random.normal(scale=3, size=anomalies2.shape)
data.append(anomalies2)
labels.append(-np.ones(50))
# Phase 3: Another shift to [-5, 5]
phase3_size = n_samples - phase1_size - phase2_size - 100
data.append(np.random.normal(loc=[-5, 5], scale=1, size=(phase3_size, 2)))
labels.append(np.ones(phase3_size))
anomalies3 = np.random.uniform(low=[-8, 3], high=[-2, 7], size=(50, 2))
anomalies3 += np.random.normal(scale=3, size=anomalies3.shape)
data.append(anomalies3)
labels.append(-np.ones(50))
X = np.vstack(data)
y = np.hstack(labels)
return X[:n_samples], y[:n_samples]
# Test 1: Static Anomaly Detection
print("=" * 60)
print("TEST 1: STATIC ANOMALY DETECTION")
print("=" * 60)
X, y = generate_synthetic_data(n_normal=1000, n_anomalies=50)
# Fit model
iso_forest = IsolationForest(
n_trees=100,
max_depth=10,
sample_size=256,
contamination=0.05
)
iso_forest.fit(X)
# Get predictions
predictions = iso_forest.predict(X)
scores = iso_forest.anomaly_score(X)
# Evaluate
n_detected_anomalies = (predictions[y == -1] == -1).sum()
anomaly_detection_rate = n_detected_anomalies / (y == -1).sum()
false_positive_rate = (predictions[y == 1] == -1).sum() / (y == 1).sum()
report = iso_forest.get_anomaly_report(X)
print(f"\nDetection Results:")
print(f"Total Anomalies (True): {(y == -1).sum()}")
print(f"Anomalies Detected: {n_detected_anomalies}")
print(f"Detection Rate: {anomaly_detection_rate:.2%}")
print(f"False Positive Rate: {false_positive_rate:.2%}")
print(f"\nThreshold: {iso_forest.threshold:.4f}")
print(f"\nScore Statistics:")
for key, value in report['score_stats'].items():
print(f" {key}: {value:.4f}")
# Visualize
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
# Plot 1: Data points colored by true label
ax = axes[0, 0]
normal_mask = y == 1
anomaly_mask = y == -1
ax.scatter(X[normal_mask, 0], X[normal_mask, 1], c='blue',
label='Normal', alpha=0.6, s=30)
ax.scatter(X[anomaly_mask, 0], X[anomaly_mask, 1], c='red',
label='Anomaly', alpha=0.8, s=50, marker='^')
ax.set_title('True Labels', fontsize=12, fontweight='bold')
ax.set_xlabel('Feature 1')
ax.set_ylabel('Feature 2')
ax.legend()
ax.grid(True, alpha=0.3)
# Plot 2: Data points colored by prediction
ax = axes[0, 1]
predicted_normal = predictions == 1
predicted_anomaly = predictions == -1
ax.scatter(X[predicted_normal, 0], X[predicted_normal, 1], c='blue',
label='Predicted Normal', alpha=0.6, s=30)
ax.scatter(X[predicted_anomaly, 0], X[predicted_anomaly, 1], c='red',
label='Predicted Anomaly', alpha=0.8, s=50, marker='^')
ax.set_title('Predictions', fontsize=12, fontweight='bold')
ax.set_xlabel('Feature 1')
ax.set_ylabel('Feature 2')
ax.legend()
ax.grid(True, alpha=0.3)
# Plot 3: Anomaly scores
ax = axes[1, 0]
scatter = ax.scatter(X[:, 0], X[:, 1], c=scores, cmap='RdYlBu_r',
s=50, alpha=0.7)
ax.axhline(y=iso_forest.threshold, color='green', linestyle='--',
label=f'Threshold: {iso_forest.threshold:.3f}')
ax.set_title('Anomaly Scores', fontsize=12, fontweight='bold')
ax.set_xlabel('Feature 1')
ax.set_ylabel('Feature 2')
plt.colorbar(scatter, ax=ax, label='Score')
ax.legend()
ax.grid(True, alpha=0.3)
# Plot 4: Score distribution
ax = axes[1, 1]
ax.hist(scores[y == 1], bins=50, alpha=0.7, label='Normal', color='blue')
ax.hist(scores[y == -1], bins=50, alpha=0.7, label='Anomaly', color='red')
ax.axvline(x=iso_forest.threshold, color='green', linestyle='--',
linewidth=2, label=f'Threshold: {iso_forest.threshold:.3f}')
ax.set_title('Score Distribution', fontsize=12, fontweight='bold')
ax.set_xlabel('Anomaly Score')
ax.set_ylabel('Frequency')
ax.legend()
ax.grid(True, alpha=0.3, axis='y')
plt.tight_layout()
plt.savefig('static_anomaly_detection.png', dpi=300, bbox_inches='tight')
plt.show()
print("\n✓ Static anomaly detection test completed!")
class AnomalyDetectionBenchmark:
"""Benchmark different detection scenarios"""
@staticmethod
def benchmark_tree_count(X: np.ndarray, y: np.ndarray,
tree_counts: List[int]) -> Dict:
"""Benchmark effect of number of trees"""
results = {}
for n_trees in tree_counts:
model = IsolationForest(n_trees=n_trees, contamination=0.05)
model.fit(X)
predictions = model.predict(X)
scores = model.anomaly_score(X)
metrics = AnomalyMetrics.evaluate(y, predictions, scores)
results[n_trees] = metrics
return results
@staticmethod
def benchmark_sample_size(X: np.ndarray, y: np.ndarray,
sample_sizes: List[int]) -> Dict:
"""Benchmark effect of sample size"""
results = {}
for size in sample_sizes:
model = IsolationForest(
n_trees=100,
sample_size=size,
contamination=0.05
)
model.fit(X)
predictions = model.predict(X)
scores = model.anomaly_score(X)
metrics = AnomalyMetrics.evaluate(y, predictions, scores)
results[size] = metrics
return results
@staticmethod
def visualize_benchmark(results: Dict, parameter_name: str,
metric: str = 'f1_score'):
"""Visualize benchmark results"""
parameters = sorted(results.keys())
metric_values = [results[p][metric] for p in parameters]
plt.figure(figsize=(10, 6))
plt.plot(parameters, metric_values, marker='o', linewidth=2,
markersize=8, color='darkblue')
plt.xlabel(parameter_name, fontsize=11)
plt.ylabel(metric, fontsize=11)
plt.title(f'Impact of {parameter_name} on {metric}',
fontsize=12, fontweight='bold')
plt.grid(True, alpha=0.3)
plt.tight_layout()
return plt.gcf()
# Run benchmarks
print("\n" + "=" * 60)
print("TEST 4: BENCHMARKING")
print("=" * 60)
benchmark = AnomalyDetectionBenchmark()
# Test different tree counts
print("\nBenchmarking number of trees...")
tree_results = benchmark.benchmark_tree_count(X, y, [10, 50, 100, 200])
print("Number of Trees vs F1-Score:")
for n_trees, metrics in sorted(tree_results.items()):
print(f" {n_trees:3d} trees: F1={metrics['f1_score']:.4f}, "
f"ROC-AUC={metrics.get('roc_auc', 'N/A')}")
fig = benchmark.visualize_benchmark(tree_results, "Number of Trees", "f1_score")
fig.savefig('benchmark_n_trees.png', dpi=300, bbox_inches='tight')
plt.show()
# Test different sample sizes
print("\nBenchmarking sample size...")
sample_results = benchmark.benchmark_sample_size(X, y, [64, 128, 256, 512])
print("Sample Size vs F1-Score:")
for size, metrics in sorted(sample_results.items()):
print(f" {size:3d} samples: F1={metrics['f1_score']:.4f}, "
f"ROC-AUC={metrics.get('roc_auc', 'N/A')}")
fig = benchmark.visualize_benchmark(sample_results, "Sample Size", "f1_score")
fig.savefig('benchmark_sample_size.png', dpi=300, bbox_inches='tight')
plt.show()
print("\n✓ Benchmarking completed!")
class AdvancedAnomalyAnalysis:
"""Advanced analysis tools for anomalies"""
@staticmethod
def feature_importance_anomalies(forest: IsolationForest,
anomaly_indices: np.ndarray,
X: np.ndarray) -> Dict:
"""Analyze which features distinguish anomalies"""
anomalies = X[anomaly_indices]
normal_indices = np.setdiff1d(np.arange(len(X)), anomaly_indices)
normal = X[normal_indices]
feature_importance = {}
for i in range(X.shape[1]):
# Statistical distance for each feature
anomaly_mean = anomalies[:, i].mean()
normal_mean = normal[:, i].mean()
anomaly_std = anomalies[:, i].std()
normal_std = normal[:, i].std()
# Effect size (similar to Cohen's d)
pooled_std = np.sqrt(
(anomaly_std**2 + normal_std**2) / 2
)
if pooled_std > 0:
effect_size = abs(anomaly_mean - normal_mean) / pooled_std
else:
effect_size = 0
feature_importance[f'Feature {i}'] = {
'effect_size': effect_size,
'anomaly_mean': anomaly_mean,
'normal_mean': normal_mean,
'diff': anomaly_mean - normal_mean
}
return feature_importance
@staticmethod
def cluster_anomalies(scores: np.ndarray, X: np.ndarray,
threshold_percentile: int = 95) -> Dict:
"""Cluster anomalies by anomaly score"""
anomaly_threshold = np.percentile(scores, threshold_percentile)
anomaly_mask = scores > anomaly_threshold
if anomaly_mask.sum() == 0:
return {'n_clusters': 0}
anomaly_scores_sorted_idx = np.argsort(scores)[::-1]
top_k = min(20, anomaly_mask.sum())
top_anomalies_idx = anomaly_scores_sorted_idx[:top_k]
return {
'n_anomalies': anomaly_mask.sum(),
'top_anomalies_indices': top_anomalies_idx,
'top_anomalies_scores': scores[top_anomalies_idx],
'threshold': anomaly_threshold
}
# Advanced analysis
print("\n" + "=" * 60)
print("TEST 5: ADVANCED ANOMALY ANALYSIS")
print("=" * 60)
# Find anomalies
anomaly_indices = np.where(predictions == -1)[0]
print(f"\nDetected {len(anomaly_indices)} anomalies")
# Feature importance
analysis = AdvancedAnomalyAnalysis()
feature_imp = analysis.feature_importance_anomalies(
iso_forest, anomaly_indices, X
)
print("\nFeature Importance for Anomalies:")
for feat, info in feature_imp.items():
print(f"{feat}:")
print(f" Effect Size: {info['effect_size']:.4f}")
print(f" Anomaly Mean: {info['anomaly_mean']:7.3f} | "
f"Normal Mean: {info['normal_mean']:7.3f}")
print(f" Difference: {info['diff']:7.3f}")
# Cluster anomalies
clusters = analysis.cluster_anomalies(scores, X)
print(f"\nTop Anomalies:")
for idx, score in zip(clusters['top_anomalies_indices'][:5],
clusters['top_anomalies_scores'][:5]):
print(f" Index {idx}: Score={score:.4f}, "
f"Position=[{X[idx, 0]:.2f}, {X[idx, 1]:.2f}]")
print("\n✓ Advanced analysis completed!")