Building Anomaly Detection Systems: A Practical Guide
Anomaly types, Isolation Forest, LOF and One-Class SVM, STL residuals for time series, autoencoders, evaluating with few labels, and routing alerts to people.
Anomaly detection means finding the data points that do not behave like the rest: a payment at an odd hour, a server metric that drifts, a sensor that goes quiet. The methods are well documented in open-source libraries. The hard parts are choosing a method that fits your data, judging it when you have few labelled incidents, and getting alerts to a person without burying them. This guide covers each step with code from official documentation, plus one small working example.
Three kinds of anomaly
It helps to name what you are hunting before picking an algorithm. Zoho’s QuickML anomaly detection docs use a common three-way split:
| Type | What it looks like | Example |
|---|---|---|
| Point | One observation sits far away from all the others | A card charge far larger than anything the customer has made before |
| Contextual | A value that is fine in one setting and wrong in another | A burst of orders that is normal during a holiday sale but odd on an ordinary day |
| Collective | Several points that each look ordinary but are unusual as a group | A share price falling on several days in a row, beyond its normal wobble |
Most off-the-shelf detectors handle point anomalies directly. Contextual and collective ones usually need you to supply the context, for example by removing seasonality first or scoring windows instead of single rows.
Unsupervised methods in scikit-learn
The scikit-learn novelty and outlier detection guide draws a distinction worth keeping in mind. Outlier detection trains on data that already contains some anomalies. Novelty detection trains on clean data and asks whether new points look different. The docs equate the first with unsupervised and the second with semi-supervised anomaly detection.
All the estimators share an interface. You call fit, then predict returns 1 for inliers and -1 for outliers. decision_function returns a score where negative means outlier, and the contamination parameter controls the threshold.
- Isolation Forest builds random trees, each split choosing a random feature and a random cut point. Anomalies get separated in fewer splits, so a short average path from root to leaf signals an unusual sample. The guide recommends it for high-dimensional data.
- Local Outlier Factor (LOF) compares how dense a point’s neighbourhood is with the density around its k nearest neighbours. A point in a much sparser patch than its neighbours scores as abnormal. Because it reasons locally, it can cope with datasets where normal regions have different densities. The docs suggest
n_neighbors=20as a reasonable default. - One-Class SVM learns a boundary around the training data, using an RBF kernel by default, and flags points that land outside it. The guide warns that it is sensitive to outliers in its training data, so it fits novelty detection better than raw outlier detection. Its
nuparameter needs tuning. For large datasets,SGDOneClassSVMis a linear version whose cost grows linearly with the number of samples.
LOF has a quirk. By default it only offers fit_predict on the training data. To score new rows you must create it with novelty=True:
from sklearn.neighbors import LocalOutlierFactor
lof = LocalOutlierFactor(novelty=True)
lof.fit(X_train)
labels = lof.predict(X_new) # 1 = inlier, -1 = outlier
For an Isolation Forest walk-through on payment-style features, see our post on what JPMorgan has said about AI in fraud detection. The example below takes a different route.
Time series: decompose, then score the residual
Metrics such as traffic, sales or sensor readings carry trends and daily or weekly cycles. A raw threshold on that kind of series will fire every busy afternoon and miss a quiet-hour surge. One standard fix is to strip out trend and seasonality and look at what is left.
statsmodels provides STL, a LOESS-based method that splits a series into trend, seasonal and residual parts. Its example notebook shows robust=True, which re-weights the data while fitting so that large errors distort the trend and seasonal fits less. Those large errors stay in the residual, which is exactly where you want your anomalies.
The script below builds four weeks of hourly checkout counts and injects one anomaly of each type. It then decomposes the series with robust STL and scores each hour’s residual against the median and median absolute deviation (MAD), so the anomalies themselves cannot inflate the scale.
import numpy as np
import pandas as pd
from statsmodels.tsa.seasonal import STL
rng = np.random.default_rng(7)
idx = pd.date_range("2026-10-01", periods=24 * 28, freq="h")
hour = idx.hour.to_numpy()
y = 200 + 120 * np.sin((hour - 9) / 24 * 2 * np.pi) + rng.normal(0, 10, len(idx))
s = pd.Series(y, index=idx)
s["2026-10-09 03:00"] = 300 # contextual: daytime volume at 3am
s["2026-10-15 14:00"] += 150 # point: sudden spike
s["2026-10-22 12:00":"2026-10-22 15:00"] -= 90 # collective: four weak hours
resid = STL(s, period=24, robust=True).fit().resid
mad = (resid - resid.median()).abs().median()
score = (resid - resid.median()).abs() / (1.4826 * mad)
print(score[score > 4].sort_values(ascending=False).round(1))
On our run, the 3am value (300) ranks first even though plenty of afternoon hours are higher. The point spike comes second and the four weak hours on 22 October follow. Then come a few ordinary hours that just clear the cutoff, which is the false-alarm problem in miniature.
If you would rather forecast than decompose, Prophet’s uncertainty intervals give a similar check: flag actuals outside yhat_lower and yhat_upper. The width is set with interval_width, which defaults to 0.8. Prophet’s docs say these intervals rest on the assumption that future trend changes resemble past ones, so you should not expect exact coverage.
Autoencoders for complex signals
When each record is a long vector, such as a waveform or image, a neural approach can help. TensorFlow’s autoencoder tutorial works through the ECG5000 dataset, which holds 5,000 electrocardiograms of 140 points each. The recipe:
- Train the autoencoder only on normal heartbeats, so it learns to rebuild those well.
- Measure reconstruction error, the mean absolute error between input and output, on the normal training set.
- Set the threshold at that mean plus one standard deviation.
- Flag any new example whose error is above the threshold.
reconstructions = autoencoder.predict(normal_train_data)
train_loss = tf.keras.losses.mae(reconstructions, normal_train_data)
threshold = np.mean(train_loss) + np.std(train_loss)
The tutorial stresses that this threshold rule is only one option, that the best choice depends on your dataset, and that shifting the threshold trades precision against recall. ECG5000 has labels, but the tutorial frames the method for cases where you have plenty of normal data and only a handful of known anomalies.
Evaluating with few labels
You rarely have a clean labelled test set. Usually you have a handful of past incidents and a team with limited time to review alerts. Two habits help.
Measure precision at k. Rank everything by anomaly score, take the top k, and count how many were real problems. Set k to the number of alerts a reviewer can actually check in a day or a shift. Appending this to the example above:
labelled = pd.to_datetime(["2026-10-09 03:00", "2026-10-15 14:00"]).append(
pd.date_range("2026-10-22 12:00", "2026-10-22 15:00", freq="h"))
top_k = score.nlargest(8)
print("precision@8:", top_k.index.isin(labelled).mean()) # 0.75 on our run
Six of the eight top hours are injected anomalies and two are noise. Recall is harder to judge with few labels, so plant synthetic anomalies like these in replayed historical data to check you catch the kinds you care about.
Treat alert fatigue as a metric. Google’s SRE book points out that paging a person costs real time and attention. It says that when pages arrive too often, people start skimming or ignoring them and can miss the real one hidden in the noise. Its SLO alerting chapter scores alert rules on precision, recall, detection time and reset time. It also shows that requiring a condition to persist before firing yields alerts that more often reflect a significant event. In the example, that would mean merging the four weak hours into one incident rather than four pages.
If data quality is a likely cause of anomalies, catch it upstream with validation checks such as those in our Great Expectations guide.
Routing alerts to humans
A detector’s output is a score. Turning that into a sensible human action is a separate design job. The SRE book’s monitoring chapter separates alerts into pages, tickets and email, and gives a few rules that carry over to ML detectors:
- Page only for urgent, actionable problems that users can see now or soon. The book argues that a page needing only a mechanical response should not be a page, so automate that response instead.
- Send lower-confidence scores to a ticket queue or a daily review list, not a pager.
- Do not alert just because something looks a bit odd. The book makes an exception only for narrow security auditing. A high anomaly score with no clear user impact belongs in a review queue.
- Keep paging rules simple so the on-call person can tell why they were woken.
- Feed reviewer verdicts back as labels. Each confirmed or dismissed alert improves your next precision@k estimate and your threshold.
For model and agent monitoring as a product rather than a script, browse the evaluation and monitoring hub, which includes platforms such as Fiddler AI.
Picking a starting point
| Your data | Start with |
|---|---|
| Tabular rows, some anomalies already in the training data | Isolation Forest or LOF (outlier detection) |
| Clean history, scoring new rows | LOF with novelty=True or One-Class SVM |
| Seasonal metric over time | Robust STL residual scores, or Prophet intervals |
| Long vectors such as waveforms or images | Autoencoder trained on normal data only |
Whatever you choose, fix the alert budget first. Set it as the number of alerts per day your team can actually review, then tune thresholds to fill that budget with the best precision you can get.
Written by AI Agents Directory
Editorial team
Facts in this guide are checked against official documentation and repositories, which are linked in the article.