Anomaly detection
How anomaly detection finds unusual measurements, events or samples using statistical, distance-based, tree-based and neural methods, and how to set thresholds and evaluate results when anomalies are rare.
What it is
Anomaly detection (also called outlier or novelty detection) is the task of identifying observations that differ markedly from the rest of the data or from what is expected. Anomalies can be errors (a faulty sensor, a typing mistake), signals of problems (a failing bearing, a fraudulent transaction, a network intrusion) or genuinely interesting discoveries (a new particle, a rare cell type). Three kinds are distinguished: point anomalies (a single value that is unusual), contextual anomalies (normal in general but odd in context, such as 30 °C in winter) and collective anomalies (a group of points that is unusual together, such as an abnormal vibration pattern). Methods are used in condition monitoring, quality control, finance and fraud, cybersecurity, healthcare, laboratory data checking and scientific surveys.
It answers questions such as: Which measurements look wrong or unusual? Is this machine behaving differently from its normal state? Which transactions or samples deserve a closer look? Has the process drifted? Because anomalies are rare and often unlabeled, the central difficulties are defining “normal”, setting a threshold, and limiting false alarms.
Fundamentals
Settings and basic statistical methods
Three learning settings occur. Supervised detection uses labeled normal and anomalous examples (rare, and unable to find new kinds of anomaly). Semi-supervised (novelty) detection trains on normal data only and flags departures. Unsupervised detection assumes that most data are normal and that anomalies are few and different. Simple statistical rules are strong baselines. The z-score, z = (x − μ)/σ, flags values beyond about ±3; because the mean and standard deviation are themselves distorted by outliers, the modified z-score uses the median and median absolute deviation, M = 0.6745 (x − median)/MAD, flagging |M| > 3.5. The IQR rule flags points outside Q1 − 1.5 × IQR and Q3 + 1.5 × IQR (the box plot whiskers). For several variables, the Mahalanobis distance accounts for correlations, and for roughly normal data its square follows a chi-square distribution, giving a principled threshold.
Distance, density, tree and boundary methods
- k-nearest-neighbor distance: points far from their neighbors are anomalous. The local outlier factor (LOF) compares a point’s local density with that of its neighbors, so it can detect anomalies in regions of varying density (LOF well above 1 is suspicious); DBSCAN labels low-density points as noise.
- Isolation forest (Liu et al., 2008): random trees split the data at random features and values; anomalies, being few and different, are isolated in fewer splits. The score is s = 2−E[h(x)]/c(n), where E[h(x)] is the average path length and c(n) a normalizer; values near 1 indicate anomalies and values below 0.5 normal points. It is fast, scales to large data and needs little tuning (mainly the expected contamination).
- One-class SVM and support vector data description: learn a boundary enclosing normal data (see support vector machines).
- PCA-based: large reconstruction error or large distance in the leading components signals anomalies (see principal component analysis).
Neural and time-series methods
An autoencoder trained on normal data reconstructs normal inputs well and anomalies poorly, so the reconstruction error is the anomaly score (see autoencoders); variational autoencoders, GAN-based detectors and deep one-class methods (Deep SVDD) extend this. For images, pretrained feature extractors with nearest-neighbor or density scoring (PatchCore) detect surface defects with few or no defective examples. For time series, the typical approach is to forecast the next values (ARIMA, exponential smoothing, LSTM; see ARIMA and RNN and LSTM) and flag points whose residuals are large; seasonal-trend decomposition (STL) removes regular patterns first; CUSUM and other change-point methods detect shifts in mean or variance; the matrix profile finds unusual subsequences; and multivariate models detect broken relationships between sensors. Contextual anomalies need the context (time of day, operating mode) as input or as a conditioning variable. Streaming data require online algorithms with adaptive baselines, because the definition of normal drifts with seasons, wear and process changes.
Thresholds, evaluation and deployment
Every method outputs a score, and a threshold turns it into an alarm. Choose it from a target false-alarm rate (for instance the 99.5th percentile of scores on normal validation data), from extreme value theory fitted to the score tail, or from the costs of missed anomalies versus false alarms. With very rare anomalies, accuracy is meaningless (predicting “normal” always gives 99.9%). Use precision, recall, F1 and the precision–recall curve (PR-AUC), which are more informative than ROC-AUC under heavy imbalance; for time series, use event-based metrics that credit detecting an anomalous interval, not each point. Labeled evaluation data are scarce, so use injected synthetic anomalies, expert review of top-ranked alerts, and several methods in agreement. Operational issues: alert fatigue from too many false positives, concept drift requiring retraining, contamination of “normal” training data with hidden anomalies, and the need for explanations (which variable deviated?), for example through feature contributions or SHAP values (see explainable AI). In science, an outlier may be an error or a discovery, so inspect it and document the decision, rather than deleting it automatically.
Typical applications and limits
Limits: the definition of anomaly is subjective, labeled data are rare, thresholds are hard, results degrade under drift, and unusual-but-harmless samples generate false alarms.
Basic operation
- Define “anomaly”. State what the unusual events are and what a miss or false alarm costs.
- Collect and clean the data. Gather normal data, handle missing values and note the context.
- Start with a simple baseline. Try z-score, IQR or a forecast residual rule.
- Apply a model. Use isolation forest, LOF or an autoencoder for multivariate data.
- Set the threshold. Use validation data and a target false-alarm rate.
- Evaluate. Use precision, recall and PR-AUC with labeled or injected anomalies.
- Review the alerts. Have an expert inspect the top-ranked cases and explain them.
- Collect the output. You obtain anomaly scores and flagged cases; threshold setting and drift handling are covered in the video.
Good practice
- Begin with simple rules. They are transparent and often strong.
- Do not trust accuracy. Use precision, recall and PR-AUC.
- Train on clean normal data. Contamination reduces sensitivity.
- Handle context and drift. Update baselines as conditions change.
- Review before removing. An outlier may be a discovery.
- Act responsibly on alerts. Flags about people, such as fraud or health alerts, should trigger human review, not automatic penalties, and in safety-critical systems the detector should supplement, not replace, protective trips and inspections.
Key terms
- Outlier — an observation far from the bulk of the data.
- Novelty detection — flagging data unlike a training set of normal examples.
- Isolation forest — a method that isolates anomalies with few random splits.
- Local outlier factor — a density-based score comparing a point with its neighbors.
- Reconstruction error — the mismatch between an input and its reconstruction, used as anomaly score.
- Contamination — the expected fraction of anomalies in the data.
- Concept drift — change over time in what counts as normal.
Video coming soon
About five minutes on Anomaly detection: how it works in detail, how the data is acquired, and how it is analyzed.
More in 4.3 AI and Machine Learning
- Regularized linear models
- Decision trees and random forests
- Gradient boosting (XGBoost)
- Support vector machines
- k-NN
- k-means
- Gaussian processes
- Neural networks
- CNNs
- RNN/LSTM
- Transformers
- Autoencoders
- GANs
- Diffusion models
- Graph neural networks
- Reinforcement learning
- Transfer learning
- Federated learning
- Explainable AI (SHAP, LIME)
- Physics-informed neural networks
- Bayesian optimization
- Active learning
- Symbolic regression
- Genetic algorithms and particle swarm optimization
- Dimensionality reduction (t-SNE, UMAP)
- NLP and large language models
- Retrieval-augmented generation
- Computer vision (detection, segmentation)
- Anomaly detection
- Machine-learned interatomic potentials
- AutoML
