Anomaly Detection

Anomaly Detection

Guides an AI coding agent to detect outliers and anomalies in data using statistical methods, isolation forests and autoencoders for fraud and quality monitoring.

Skill files3 files

scripts/

templates/

SKILL.md313 lines
1
---
2
name: Anomaly Detection
3
description: Identify unusual patterns, outliers, and anomalies in data using statistical methods, isolation forests, and autoencoders for fraud detection and quality monitoring
4
---
5
6
# Anomaly Detection
7
8
## Overview
9
10
Anomaly detection identifies unusual patterns, outliers, and anomalies in data that deviate significantly from normal behavior, enabling fraud detection and system monitoring.
11
12
## When to Use
13
14
- Detecting fraudulent transactions or suspicious activity in financial data
15
- Identifying system failures, network intrusions, or security breaches
16
- Monitoring manufacturing quality and identifying defective products
17
- Finding unusual patterns in healthcare data or patient vital signs
18
- Detecting abnormal sensor readings in IoT or industrial systems
19
- Identifying outliers in customer behavior for targeted intervention
20
21
## Detection Methods
22
23
- **Statistical**: Z-score, IQR, modified Z-score
24
- **Distance-based**: K-nearest neighbors, Local Outlier Factor
25
- **Isolation**: Isolation Forest
26
- **Density-based**: DBSCAN
27
- **Deep Learning**: Autoencoders, GANs
28
29
## Anomaly Types
30
31
- **Point Anomalies**: Single unusual records
32
- **Contextual**: Unusual in specific context
33
- **Collective**: Unusual patterns in sequences
34
- **Novel Classes**: Completely new patterns
35
36
## Implementation with Python
37
38
```python
39
import pandas as pd
40
import numpy as np
41
import matplotlib.pyplot as plt
42
import seaborn as sns
43
from sklearn.preprocessing import StandardScaler
44
from sklearn.ensemble import IsolationForest
45
from sklearn.neighbors import LocalOutlierFactor
46
from sklearn.covariance import EllipticEnvelope
47
from scipy import stats
48
49
# Generate sample data with anomalies
50
np.random.seed(42)
51
52
# Normal data
53
n_normal = 950
54
normal_data = np.random.normal(100, 15, (n_normal, 2))
55
56
# Anomalies
57
n_anomalies = 50
58
anomalies = np.random.uniform(0, 200, (n_anomalies, 2))
59
anomalies[n_anomalies//2:, 0] = np.random.uniform(80, 120, n_anomalies//2)
60
anomalies[n_anomalies//2:, 1] = np.random.uniform(-50, 0, n_anomalies//2)
61
62
X = np.vstack([normal_data, anomalies])
63
y_true = np.hstack([np.zeros(n_normal), np.ones(n_anomalies)])
64
65
df = pd.DataFrame(X, columns=['Feature1', 'Feature2'])
66
df['is_anomaly_true'] = y_true
67
68
print("Data Summary:")
69
print(f"Normal samples: {n_normal}")
70
print(f"Anomalies: {n_anomalies}")
71
print(f"Total: {len(df)}")
72
73
# Standardize
74
scaler = StandardScaler()
75
X_scaled = scaler.fit_transform(X)
76
77
# 1. Statistical Methods (Z-score)
78
z_scores = np.abs(stats.zscore(X))
79
z_anomaly_mask = (z_scores > 3).any(axis=1)
80
df['z_score_anomaly'] = z_anomaly_mask
81
82
print(f"\n1. Z-score Method:")
83
print(f"Anomalies detected: {z_anomaly_mask.sum()}")
84
print(f"Accuracy: {(z_anomaly_mask == y_true).mean():.2%}")
85
86
# 2. Isolation Forest
87
iso_forest = IsolationForest(contamination=n_anomalies/len(df), random_state=42)
88
iso_predictions = iso_forest.fit_predict(X_scaled)
89
iso_anomaly_mask = iso_predictions == -1
90
iso_scores = iso_forest.score_samples(X_scaled)
91
92
df['iso_anomaly'] = iso_anomaly_mask
93
df['iso_score'] = iso_scores
94
95
print(f"\n2. Isolation Forest:")
96
print(f"Anomalies detected: {iso_anomaly_mask.sum()}")
97
print(f"Accuracy: {(iso_anomaly_mask == y_true).mean():.2%}")
98
99
# 3. Local Outlier Factor
100
lof = LocalOutlierFactor(n_neighbors=20, contamination=n_anomalies/len(df))
101
lof_predictions = lof.fit_predict(X_scaled)
102
lof_anomaly_mask = lof_predictions == -1
103
lof_scores = lof.negative_outlier_factor_
104
105
df['lof_anomaly'] = lof_anomaly_mask
106
df['lof_score'] = lof_scores
107
108
print(f"\n3. Local Outlier Factor:")
109
print(f"Anomalies detected: {lof_anomaly_mask.sum()}")
110
print(f"Accuracy: {(lof_anomaly_mask == y_true).mean():.2%}")
111
112
# 4. Elliptic Envelope (Robust Covariance)
113
ee = EllipticEnvelope(contamination=n_anomalies/len(df), random_state=42)
114
ee_predictions = ee.fit_predict(X_scaled)
115
ee_anomaly_mask = ee_predictions == -1
116
ee_scores = ee.mahalanobis(X_scaled)
117
118
df['ee_anomaly'] = ee_anomaly_mask
119
df['ee_score'] = ee_scores
120
121
print(f"\n4. Elliptic Envelope:")
122
print(f"Anomalies detected: {ee_anomaly_mask.sum()}")
123
print(f"Accuracy: {(ee_anomaly_mask == y_true).mean():.2%}")
124
125
# 5. IQR Method
126
Q1 = np.percentile(X, 25, axis=0)
127
Q3 = np.percentile(X, 75, axis=0)
128
IQR = Q3 - Q1
129
lower_bound = Q1 - 1.5 * IQR
130
upper_bound = Q3 + 1.5 * IQR
131
132
iqr_anomaly_mask = ((X < lower_bound) | (X > upper_bound)).any(axis=1)
133
df['iqr_anomaly'] = iqr_anomaly_mask
134
135
print(f"\n5. IQR Method:")
136
print(f"Anomalies detected: {iqr_anomaly_mask.sum()}")
137
print(f"Accuracy: {(iqr_anomaly_mask == y_true).mean():.2%}")
138
139
# Visualization of anomaly detection methods
140
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
141
142
methods = [
143
(z_anomaly_mask, 'Z-score', None),
144
(iso_anomaly_mask, 'Isolation Forest', iso_scores),
145
(lof_anomaly_mask, 'LOF', lof_scores),
146
(ee_anomaly_mask, 'Elliptic Envelope', ee_scores),
147
(iqr_anomaly_mask, 'IQR', None),
148
]
149
150
# True anomalies
151
ax = axes[0, 0]
152
colors = ['blue' if not a else 'red' for a in y_true]
153
ax.scatter(df['Feature1'], df['Feature2'], c=colors, alpha=0.6, s=30)
154
ax.set_title('True Anomalies')
155
ax.set_xlabel('Feature 1')
156
ax.set_ylabel('Feature 2')
157
158
# Plot each method
159
for idx, (anomaly_mask, method_name, scores) in enumerate(methods):
160
ax = axes.flatten()[idx + 1]
161
162
if scores is not None:
163
scatter = ax.scatter(df['Feature1'], df['Feature2'], c=scores, cmap='RdYlBu_r', alpha=0.6, s=30)
164
plt.colorbar(scatter, ax=ax, label='Score')
165
else:
166
colors = ['red' if a else 'blue' for a in anomaly_mask]
167
ax.scatter(df['Feature1'], df['Feature2'], c=colors, alpha=0.6, s=30)
168
169
ax.set_title(f'{method_name}\n({anomaly_mask.sum()} anomalies)')
170
ax.set_xlabel('Feature 1')
171
ax.set_ylabel('Feature 2')
172
173
plt.tight_layout()
174
plt.show()
175
176
# 6. Anomaly score comparison
177
fig, axes = plt.subplots(2, 2, figsize=(14, 8))
178
179
# ISO Forest scores
180
axes[0, 0].hist(iso_scores[~y_true], bins=30, alpha=0.7, label='Normal', color='blue')
181
axes[0, 0].hist(iso_scores[y_true == 1], bins=10, alpha=0.7, label='Anomaly', color='red')
182
axes[0, 0].set_xlabel('Anomaly Score')
183
axes[0, 0].set_title('Isolation Forest Score Distribution')
184
axes[0, 0].legend()
185
axes[0, 0].grid(True, alpha=0.3)
186
187
# LOF scores
188
axes[0, 1].hist(lof_scores[~y_true], bins=30, alpha=0.7, label='Normal', color='blue')
189
axes[0, 1].hist(lof_scores[y_true == 1], bins=10, alpha=0.7, label='Anomaly', color='red')
190
axes[0, 1].set_xlabel('Anomaly Score')
191
axes[0, 1].set_title('LOF Score Distribution')
192
axes[0, 1].legend()
193
axes[0, 1].grid(True, alpha=0.3)
194
195
# ROC-like curve for Isolation Forest
196
iso_scores_sorted = np.sort(iso_scores)
197
detected_at_threshold = []
198
for threshold in iso_scores_sorted:
199
detected = (iso_scores <= threshold).sum()
200
true_detected = ((iso_scores <= threshold) & (y_true == 1)).sum()
201
if detected > 0:
202
precision = true_detected / detected
203
recall = true_detected / n_anomalies
204
detected_at_threshold.append({'Threshold': threshold, 'Precision': precision, 'Recall': recall})
205
206
if detected_at_threshold:
207
threshold_df = pd.DataFrame(detected_at_threshold)
208
axes[1, 0].plot(threshold_df['Recall'], threshold_df['Precision'], linewidth=2)
209
axes[1, 0].set_xlabel('Recall')
210
axes[1, 0].set_ylabel('Precision')
211
axes[1, 0].set_title('Precision-Recall Curve (Isolation Forest)')
212
axes[1, 0].grid(True, alpha=0.3)
213
214
# Method comparison
215
methods_comparison = pd.DataFrame({
216
'Method': ['Z-score', 'Isolation Forest', 'LOF', 'Elliptic Envelope', 'IQR'],
217
'Accuracy': [
218
(z_anomaly_mask == y_true).mean(),
219
(iso_anomaly_mask == y_true).mean(),
220
(lof_anomaly_mask == y_true).mean(),
221
(ee_anomaly_mask == y_true).mean(),
222
(iqr_anomaly_mask == y_true).mean(),
223
]
224
})
225
226
axes[1, 1].barh(methods_comparison['Method'], methods_comparison['Accuracy'], color='steelblue', edgecolor='black')
227
axes[1, 1].set_xlabel('Accuracy')
228
axes[1, 1].set_title('Method Comparison')
229
axes[1, 1].set_xlim([0, 1])
230
for i, v in enumerate(methods_comparison['Accuracy']):
231
axes[1, 1].text(v, i, f' {v:.2%}', va='center')
232
233
plt.tight_layout()
234
plt.show()
235
236
# 7. Ensemble anomaly detection
237
# Combine multiple methods
238
ensemble_votes = (z_anomaly_mask.astype(int) +
239
iso_anomaly_mask.astype(int) +
240
lof_anomaly_mask.astype(int) +
241
ee_anomaly_mask.astype(int) +
242
iqr_anomaly_mask.astype(int))
243
244
df['ensemble_votes'] = ensemble_votes
245
ensemble_anomaly = ensemble_votes >= 3 # Majority vote
246
247
print(f"\n6. Ensemble (Majority Vote):")
248
print(f"Anomalies detected: {ensemble_anomaly.sum()}")
249
print(f"Accuracy: {(ensemble_anomaly == y_true).mean():.2%}")
250
251
# Visualize ensemble
252
fig, ax = plt.subplots(figsize=(10, 8))
253
scatter = ax.scatter(df['Feature1'], df['Feature2'], c=ensemble_votes, cmap='RdYlGn_r',
254
s=100 * (ensemble_anomaly.astype(int) + 0.5), alpha=0.6, edgecolors='black')
255
ax.set_xlabel('Feature 1')
256
ax.set_ylabel('Feature 2')
257
ax.set_title('Ensemble Anomaly Detection (Color: Vote Count, Size: Anomaly)')
258
cbar = plt.colorbar(scatter, ax=ax, label='Number of Methods')
259
plt.show()
260
261
# 8. Time-series anomalies
262
time_series_data = np.sin(np.arange(100) * 0.2) * 10 + 100
263
time_series_data = time_series_data + np.random.normal(0, 2, 100)
264
# Add anomalies
265
time_series_data[25] = 150
266
time_series_data[50] = 50
267
time_series_data[75] = 140
268
269
# Detect using rolling statistics
270
rolling_mean = pd.Series(time_series_data).rolling(window=5).mean()
271
rolling_std = pd.Series(time_series_data).rolling(window=5).std()
272
z_scores_ts = np.abs((time_series_data - rolling_mean) / rolling_std) > 2
273
274
fig, ax = plt.subplots(figsize=(12, 5))
275
ax.plot(time_series_data, linewidth=1, label='Data')
276
ax.plot(rolling_mean, linewidth=2, label='Rolling Mean')
277
ax.scatter(np.where(z_scores_ts)[0], time_series_data[z_scores_ts], color='red', s=100, label='Anomalies', zorder=5)
278
ax.fill_between(range(len(time_series_data)), rolling_mean - 2*rolling_std, rolling_mean + 2*rolling_std,
279
alpha=0.2, label='±2 Std Dev')
280
ax.set_xlabel('Time')
281
ax.set_ylabel('Value')
282
ax.set_title('Time-Series Anomaly Detection')
283
ax.legend()
284
ax.grid(True, alpha=0.3)
285
plt.tight_layout()
286
plt.show()
287
288
print("\nAnomaly detection analysis complete!")
289
```
290
291
## Method Selection Guide
292
293
- **Z-score**: Simple, fast, assumes normal distribution
294
- **IQR**: Robust, non-parametric, good for outliers
295
- **Isolation Forest**: Efficient, good for high dimensions
296
- **LOF**: Density-based, finds local anomalies
297
- **Autoencoders**: Complex patterns, deep learning
298
299
## Threshold Selection
300
301
- **Conservative**: Fewer false positives, more false negatives
302
- **Aggressive**: More anomalies flagged, more false positives
303
- **Data-driven**: Use validation set to optimize threshold
304
305
## Deliverables
306
307
- Anomaly detection results
308
- Anomaly scores visualization
309
- Comparison of methods
310
- Identified anomalous records
311
- Recommendation for production deployment
312
- Threshold optimization analysis
313

© AJ Geddes · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…