Detecting Data Anomalies
Overview
Identify anomalies and outliers in datasets using statistical and machine learning algorithms including Isolation Forest, One-Class SVM, Local Outlier Factor, and autoencoders. This skill handles the full detection pipeline from data ingestion and feature scaling through algorithm selection, threshold tuning, and result interpretation with anomaly scoring.
Prerequisites
- Python 3.9+ with scikit-learn >= 1.3 (
pip install scikit-learn)
- pandas and NumPy for data manipulation (
pip install pandas numpy)
- matplotlib or seaborn for anomaly visualizations (
pip install matplotlib seaborn)
- Dataset in CSV, JSON, Parquet, or database-queryable format
- Minimum 500 data points for statistical significance (1000+ recommended)
- Optional: PyTorch or TensorFlow for autoencoder-based detection on complex patterns
Instructions
- Load the dataset using the Read tool and verify schema, column types, and row count
- Profile feature distributions using descriptive statistics to understand baseline behavior
- Handle missing values via imputation (median for numeric, mode for categorical) or row exclusion
- Apply StandardScaler or MinMaxScaler to numeric features to normalize magnitude differences
- Select the detection algorithm based on data characteristics:
- Isolation Forest: high-dimensional data, no assumptions on distribution
- One-Class SVM: well-defined normal class with clear decision boundary
- Local Outlier Factor: density-varying data with local anomaly patterns
- Autoencoder: complex temporal or image data with non-linear relationships
- Set the contamination parameter to the expected anomaly proportion (start with 0.01-0.05)
- Fit the model on the training partition and generate anomaly scores for each data point
- Apply the decision threshold to classify points as normal (-1) or anomalous (1)
- Analyze flagged anomalies for common characteristics, temporal clusters, or feature correlations
- Generate a summary report with detection counts, score distributions, and visualization plots
See ${CLAUDE_SKILL_DIR}/references/implementation.md for the detailed implementation guide.
Output
- Anomaly detection summary: total points, anomaly count, contamination rate
- Per-record anomaly scores with classification labels
- Algorithm configuration: model type, contamination, distance metric, threshold
- Feature importance ranking showing which dimensions drive anomaly flags
- Visualization: scatter plot of anomaly scores, distribution histogram, t-SNE cluster plot
- CSV export of flagged records with anomaly scores and contributing features
Error Handling
| Error |
Cause |
Solution |
| Insufficient data volume |
Fewer than 100 data points for model fitting |
Collect additional data or switch to simple statistical methods (z-score, IQR) |
| High false positive rate |
Contamination parameter set too high or features not scaled |
Lower contamination to 0.01; verify StandardScaler applied; refine feature selection |
| Algorithm OOM on large dataset |
Isolation Forest or LOF exceeds available memory |
Subsample data for training; use max_samples parameter; switch to streaming approach |
| Feature scaling mismatch |
Mixed numeric and categorical features without proper encoding |
One-hot encode categoricals separately; scale numeric features independently |
| No ground truth for validation |
Unlabeled dataset prevents accuracy measurement |
Use domain expert review on top-N anomalies; implement feedback loop to refine threshold |
See ${CLAUDE_SKILL_DIR}/references/errors.md for the full error reference.
Examples
Scenario 1: Network Intrusion Detection -- Apply Isolation Forest to 50K network flow records with features: packet count, byte volume, duration, protocol type. Expected contamination: 2%. Target: flag port-scan and DDoS patterns with precision above 0.85.
Scenario 2: Manufacturing Quality Control -- Run LOF on sensor readings (temperature, vibration, pressure) from 10K production cycles. Detect equipment degradation anomalies. Visualize flagged cycles on a time-series plot with normal operating bands.
Scenario 3: Financial Transaction Monitoring -- Train an autoencoder on 100K legitimate transactions. Reconstruct test transactions and flag those with reconstruction error above the 99th percentile. Report flagged transactions with amount, merchant category, and time-of-day features.
Resources
- scikit-learn Anomaly Detection -- Isolation Forest, LOF, One-Class SVM
- PyOD Library -- 40+ outlier detection algorithms with unified API
- Autoencoder anomaly detection: Keras/PyTorch reconstruction-error approach
- Feature scaling: StandardScaler, RobustScaler, MinMaxScaler selection guide
- Evaluation without labels: silhouette analysis, domain expert review protocols
1---
2name: detecting-data-anomalies-2
3description: |
4 Process identify anomalies and outliers in datasets using machine learning algorithms.
5 Use when analyzing data for unusual patterns, outliers, or unexpected deviations from normal behavior.
6 Trigger with phrases like "detect anomalies", "find outliers", or "identify unusual patterns".
7
8allowed-tools: Read, Bash(python:*), Grep, Glob
9version: 1.0.0
10author: Jeremy Longshore <jeremy@intentsolutions.io>
11license: MIT
12compatible-with: claude-code, codex, openclaw
13tags: [ai, ml, detecting-data]
14
15---
16
17# Detecting Data Anomalies
18
19## Overview
20
21Identify anomalies and outliers in datasets using statistical and machine learning algorithms including Isolation Forest, One-Class SVM, Local Outlier Factor, and autoencoders. This skill handles the full detection pipeline from data ingestion and feature scaling through algorithm selection, threshold tuning, and result interpretation with anomaly scoring.
22
23## Prerequisites
24
25- Python 3.9+ with scikit-learn >= 1.3 (`pip install scikit-learn`)
26- pandas and NumPy for data manipulation (`pip install pandas numpy`)
27- matplotlib or seaborn for anomaly visualizations (`pip install matplotlib seaborn`)
28- Dataset in CSV, JSON, Parquet, or database-queryable format
29- Minimum 500 data points for statistical significance (1000+ recommended)
30- Optional: PyTorch or TensorFlow for autoencoder-based detection on complex patterns
31
32## Instructions
33
341. Load the dataset using the Read tool and verify schema, column types, and row count
352. Profile feature distributions using descriptive statistics to understand baseline behavior
363. Handle missing values via imputation (median for numeric, mode for categorical) or row exclusion
374. Apply StandardScaler or MinMaxScaler to numeric features to normalize magnitude differences
385. Select the detection algorithm based on data characteristics:
39 - **Isolation Forest**: high-dimensional data, no assumptions on distribution
40 - **One-Class SVM**: well-defined normal class with clear decision boundary
41 - **Local Outlier Factor**: density-varying data with local anomaly patterns
42 - **Autoencoder**: complex temporal or image data with non-linear relationships
436. Set the contamination parameter to the expected anomaly proportion (start with 0.01-0.05)
447. Fit the model on the training partition and generate anomaly scores for each data point
458. Apply the decision threshold to classify points as normal (-1) or anomalous (1)
469. Analyze flagged anomalies for common characteristics, temporal clusters, or feature correlations
4710. Generate a summary report with detection counts, score distributions, and visualization plots
48
49See `${CLAUDE_SKILL_DIR}/references/implementation.md` for the detailed implementation guide.
50
51## Output
52
53- Anomaly detection summary: total points, anomaly count, contamination rate
54- Per-record anomaly scores with classification labels
55- Algorithm configuration: model type, contamination, distance metric, threshold
56- Feature importance ranking showing which dimensions drive anomaly flags
57- Visualization: scatter plot of anomaly scores, distribution histogram, t-SNE cluster plot
58- CSV export of flagged records with anomaly scores and contributing features
59
60## Error Handling
61
62| Error | Cause | Solution |
63|-------|-------|----------|
64| Insufficient data volume | Fewer than 100 data points for model fitting | Collect additional data or switch to simple statistical methods (z-score, IQR) |
65| High false positive rate | Contamination parameter set too high or features not scaled | Lower contamination to 0.01; verify StandardScaler applied; refine feature selection |
66| Algorithm OOM on large dataset | Isolation Forest or LOF exceeds available memory | Subsample data for training; use `max_samples` parameter; switch to streaming approach |
67| Feature scaling mismatch | Mixed numeric and categorical features without proper encoding | One-hot encode categoricals separately; scale numeric features independently |
68| No ground truth for validation | Unlabeled dataset prevents accuracy measurement | Use domain expert review on top-N anomalies; implement feedback loop to refine threshold |
69
70See `${CLAUDE_SKILL_DIR}/references/errors.md` for the full error reference.
71
72## Examples
73
74**Scenario 1: Network Intrusion Detection** -- Apply Isolation Forest to 50K network flow records with features: packet count, byte volume, duration, protocol type. Expected contamination: 2%. Target: flag port-scan and DDoS patterns with precision above 0.85.
75
76**Scenario 2: Manufacturing Quality Control** -- Run LOF on sensor readings (temperature, vibration, pressure) from 10K production cycles. Detect equipment degradation anomalies. Visualize flagged cycles on a time-series plot with normal operating bands.
77
78**Scenario 3: Financial Transaction Monitoring** -- Train an autoencoder on 100K legitimate transactions. Reconstruct test transactions and flag those with reconstruction error above the 99th percentile. Report flagged transactions with amount, merchant category, and time-of-day features.
79
80## Resources
81
82- [scikit-learn Anomaly Detection](https://scikit-learn.org/stable/modules/outlier_detection.html) -- Isolation Forest, LOF, One-Class SVM
83- [PyOD Library](https://pyod.readthedocs.io/) -- 40+ outlier detection algorithms with unified API
84- Autoencoder anomaly detection: Keras/PyTorch reconstruction-error approach
85- Feature scaling: StandardScaler, RobustScaler, MinMaxScaler selection guide
86- Evaluation without labels: silhouette analysis, domain expert review protocols