Anomaly detection in machine learning flags the data points, sequences or patterns that do not fit expected behaviour and are rare compared with everything else. Isolation forest anomaly detection gets there without explicitly modelling the normal data distribution. It builds random trees that split the data on randomly chosen features and values, and a reading that gets isolated in very few splits scores as anomalous. For an operations team watching sensor readings, grid telemetry or system metrics, the score is only half the job. The other half is choosing where to cut it, and checking whether a plain threshold would have done the work anyway.
How Isolation Forest Anomaly Detection Scores a Sensor Reading
Liu et al. proposed the isolation forest, and it relies on two properties of anomalies: there are few of them, and they are different. Each tree picks a feature at random, then a split value at random between that feature’s minimum and maximum, and repeats this recursively to isolate samples. The number of splits needed to isolate a sample equals its path length from the root to its leaf. Averaged over the forest, that path length measures normality, and random partitioning gives anomalies noticeably shorter paths. When several observations share a leaf, the average path length of a tree built on that many samples is added to the depth.
The path length is normalised into a score:
s(x, n) = 2^(−E[h(x)] / c(n)), where c(n) = 2H(n−1) − 2(n−1)/n and H(k) ≈ ln(k) + 0.5772.
Here E[h(x)] is the average path length of point x across all trees, and c(n) is the average path length of an unsuccessful search in a binary search tree of n nodes. A score near 1 means the point is easy to isolate and very likely anomalous, a score near 0.5 carries no anomaly signal, and a score below 0.5 means the point is buried deep in the data.
Worked Example: Turning Path Length into a Score
- H(255) ≈ ln(255) + 0.5772 ≈ 5.541 + 0.577 = 6.118.
- c(256) = 2 × 6.118 − 2 × 255/256 ≈ 12.237 − 1.992 = 10.245.
- A meter reading isolated after 2 splits on average: s = 2^(−2/10.245) = 2^(−0.195) ≈ 0.87, so a strong anomaly signal.
- A reading with an average path of 10.245 (equal to c(n)): s = 2^(−1) = 0.5, so no signal.
- A reading with an average path of 20: s = 2^(−1.952) ≈ 0.26, which is very normal.
What the example shows is that the score compares a point’s average path length with c(n), the average path length expected for a sample of that size.
A systematic review of energy applications says isolation methods arose because statistical and nearest-neighbour approaches lose performance on high-dimensional data with varying densities, which isolation measures handle better. In a separate comparison across ten datasets, local algorithms such as LOF raised many false positives when the task was to find global anomalies. If you want a wider map of the method families and how they fit operational workloads, our guide to machine learning algorithms for anomaly detection covers them.
Reading Scikit-Learn’s IsolationForest Output
The scikit-learn implementation inverts the direction of the 0-to-1 score above. In its raw scores, inliers sit close to 0 and outliers close to −1, and with contamination="auto" the offset is −0.5. In scikit-learn’s scores, the lower the value the more abnormal: negative values are outliers and positive values are inliers. fit_predict returns −1 for outliers and 1 for inliers. In the paper’s convention a higher score means more anomalous, while in scikit-learn a lower one does.
The contamination parameter defines the threshold, even though it does not look like one. It states the expected proportion of outliers, it is used at fit time to set the cut on the scores, and it takes either "auto" (the original paper’s threshold) or a float in (0, 0.5]. With a float, the offset is placed so that the expected number of training samples get a negative decision function. Set it to 0.01 and the model will call 1% of the training data outliers, whatever that data actually contains. A lower contamination flags only the most extreme points. A higher one catches borderline cases and produces more false positives. The method works best when anomalies make up a small fraction of the data, and any unsupervised technique that assumes normal points vastly outnumber anomalies suffers a high false alarm rate when that assumption fails.
The safer route is to keep the raw scores, look at their distribution, and set the cut from how many alerts the team can actually investigate. Accepting a contamination value because it looked like a sensible default is the riskier choice.
What Counts as an Anomaly in Operational Data, and What Is Just Noise or a Known Fault?
In operational data, whether a deviation counts as an anomaly depends on who consumes the alert and how. Noise is a deviation the analyst has no interest in and that gets in the way of the analysis. Whether an event counts as an anomaly is not a property of the data. It depends on the application: the same event can be anomalous in one setting and normal in another.
An industry case on refrigerated cooling units makes this concrete. A temporary power outage caused a low-temperature excursion and a door left open caused a high one. Both are statistically significant anomalies, yet only the door event is likely to matter operationally. Short, extreme temperature spikes from the same units are physically implausible, so they are measurement errors rather than real temperature changes, and the sensor needs replacing. That matters to device maintenance and is irrelevant to the logistics team. Sensor networks carry the same ambiguity, because an anomalous reading can mean a faulty sensor or a real event, and noise and missing values make the two harder to separate.
Known faults are a third category. Point anomalies such as a momentary malfunction in data acquisition or transmission are generally considered alarm triggers handled from predefined knowledge, while contextual and collective anomalies often lead to the discovery of new behavioural patterns. Where labelled normal and abnormal examples exist, supervised techniques train a binary classifier on them. Anomaly detection earns its place on the failures you cannot list in advance. When the failures are visual, such as surface defects on a line, our computer vision R&D work covers image-based detection.
The shape of the deviation matters for the method you pick:
- Point anomalies: a single spike or glitch, often from acquisition errors or hardware failures.
- Contextual anomalies: normal in isolation but wrong for their context. A 26°C reading is ordinary over a year but anomalous in winter.
- Subsequence or collective anomalies: consecutive points that are unremarkable one by one but together show something like gradual degradation, and finding them requires techniques that account for temporal correlation.
An isolation forest scores each row on its own, so it only sees context you put into the features. One approach is to identify the context first and then score the point within that context. That requires contextual attributes, most commonly time, alongside the behavioural ones.
An Anomaly Detection Example from Smart Meters and Grid Telemetry
Smart-meter data shows what the work looks like at utility scale. A study of anonymised records from around 120,000 UK smart meters, with daily electricity consumption in 48 half-hour bins and time-stamped event codes over three months, was motivated by meter-tampering theft as up to 50 million smart meters were being deployed across the UK. Using a density analysis of the joint distribution of distances, the authors found 560 cases (under 0.5%) beyond two standard deviations from the background process. They treated these as strongly indicating a different generating mechanism. That method is a density analysis, not an isolation forest. The example still shows the scale of the haystack, and that the cut-off (here d > 2) is a choice someone has to defend.
Grid telemetry adds topology. One method tested on 24 hours of state-estimation output from a real utility in the US Eastern Interconnect, at half-hour intervals, estimates a distribution of normal values for each sensor and raises an alarm when a measurement deviates far from its centre. It uses weighted median and interquartile range rather than mean and variance, because those are robust to the anomalies themselves. The authors say plainly that rare legitimate events such as active load-shedding may be flagged, and that clearing those false positives is left to operators, who have the extra context.
Isolation forest draws growing interest in this sector. A systematic review of energy applications found it used both as the main detection technique and as the benchmark for evaluating new methods on electricity consumption data. The same review reports a wind-turbine power-curve study comparing iForest, LOF, Gaussian mixture models and k-NN, in which Gaussian mixtures stood out. The literature does not settle the comparison: the review suggests isolation-based methods may be emerging as the new benchmark against statistical approaches, but also cites work holding that statistical methods perform better long term because AI-based models struggle as operating conditions change with system wear. We read that as a reason to run both on your own history before committing to either. For how these pieces fit together across plant and grid operations, see our article on how anomaly detection works in industrial and energy operations.
Should Your Telemetry Use a 3σ Threshold or an Isolation Forest Score?
A fixed threshold is enough when the metric is roughly stationary, its normal range is known, and the alert has to be explainable to the person who receives it. The classic rule from process quality control flags anything more than 3σ from the mean, a band that holds 99.7% of Gaussian data. The box-plot rule (1.5 × IQR beyond the quartiles) is equivalent to 3σ for Gaussian data. A threshold like “two standard deviations from the mean” is easy to explain and easy to draw on a chart.
In the Yahoo benchmark, 316 of 367 time series (86.1%) could be solved with a simple expression built from moving means and standard deviations. Google’s SRE guidance makes the operational argument: the rules that catch real incidents most often should be as simple, predictable and reliable as possible. Industrial alarm practice has its own standard. ISA-18.2 treats alarm response as a human-machine interaction and lists model-based alarming and continuously variable thresholds among the advanced methods.
Fixed thresholds go stale on trending or seasonal metrics. Datadog’s documentation gives the example of logins on a steadily growing site, where any fixed threshold soon becomes outdated, and web traffic that is abnormally low on a weekday afternoon but normal in the evening. Datadog’s seasonal algorithms need at least three times the seasonal period of history, so three weeks of data for weekly seasonality. Scale is the other push. Operational estates can carry millions of metrics, and the data is noisy and heavily imbalanced. Rare combinations are a third case, because a method that scores each attribute separately cannot see a combination of individually common values that is rare as a whole.
Decision Table: Threshold or Model
| Situation in your telemetry | Start with | Why |
|---|---|---|
| Single metric, stable range, spikes are the failure | 3σ or IQR rule | Explainable, cheap, matches point anomalies |
| Metric with trend or daily/weekly seasonality | Seasonal baseline or forecast residual | Fixed thresholds go stale on trending metrics |
| Seasonal metric, short history | Rolling-quantile band until history builds | Datadog’s seasonal algorithms need three seasonal periods of data |
| Many correlated sensors, failure shows as an odd combination | Multivariate scoring, not attribute-wise histograms | Attribute-wise methods miss rare combinations |
| Regions of very different density in feature space | Isolation-based scoring | Review reports better handling of varying density |
| Known fault with labelled examples | Classifier or explicit rule | Supervised methods suit cases where labels exist |
Which Metrics Show Whether Your Detector Is Catching Real Faults?
Accuracy is unsuitable for anomaly detection. With 90 normal samples and 10 anomalies, a detector that labels everything normal scores 90% accuracy while finding nothing. AUC has a direct reading: the probability that the detector scores a randomly chosen anomaly above a randomly chosen normal instance. Precision and recall both focus on the anomaly class. Precision tells you how many alerts were correct, and recall how many of the real anomalies you caught.
Alert Fatigue Decides Whether the Detector Survives
An alerting feature with a high false-positive rate is likely to be ignored before long, and suppressing spurious alerts is critical to user trust. At volume the arithmetic is brutal: across millions of data objects, a few percent of false alarms can overwhelm an analyst. Google’s SRE book names the result “alert spam”: alerts that are rarely read or acted on. Datadog alerts trigger when values stay out of bounds for a chosen window, and a window that is too short produces false alarms from spurious noise.
Our position is that operational anomaly detection is a production reliability surface as much as a modelling problem. The work that keeps it trustworthy is alert-quality engineering. The specific artefacts are set out in our piece on what makes an operational anomaly detection system trustworthy, and the signals to instrument once normal behaviour starts to move are in drift telemetry for anomaly systems beyond a classical model.
Before you build a forest, the question to settle is how many alerts a week your operators can investigate properly, and which events they would thank you for waking them over. That number sets the threshold. Contamination, path length and AUC only help you hit it.
FAQ
What Is an Anomaly in Data Analytics?
In data analytics, an anomaly is an observation that deviates so far from the others that it suggests a different generating mechanism. That is Hawkins’s well-known 1980 definition. Analysts often pick out an anomaly from a ranked list of scores, either by inspecting the top few or by applying a cut-off threshold.