Anomaly detection with thresholds and isolation forests
Compare z-score thresholds and an isolation forest on synthetic data and estimate the false alert rate each produces.
By Invicly Tech, , in AI and Machine Learning with Python. About 13 minutes to read.
In short
Anomaly detection gives each row a score for how unusual it looks, then a threshold turns scores into alerts. Simple statistical rules such as z-scores work well for one well-behaved number, while an isolation forest can score rows across many features. Every threshold trades missed incidents against false alerts, and the alert volume decides whether anyone keeps watching.
Think of it like this: An anomaly detector is a smoke alarm: set it too sensitive and people pull the battery out; set it too dull and it misses the fire.
Explained simply
An anomaly is a data point that does not fit the usual pattern: a payment ten times bigger than normal, a server suddenly using all its memory, a sensor reading of minus 400 degrees. Anomaly detection tries to find these automatically, usually without a list of past examples to learn from.
Most detectors work in two steps. First they give every row a score for how unusual it looks. Then a threshold turns the score into a yes or no: alert, or no alert. The scoring method gets the attention, but the threshold decides how many alerts people receive.
The simplest score is the z-score: how many standard deviations a value is from the average. A common rule is to alert above 3. It is easy to explain and works for one roughly bell-shaped number. For many columns at once, an isolation forest is a good next step. It builds random trees and notices which points are easy to cut off from the rest.
Every threshold makes two kinds of mistake. It can miss a real problem, or it can raise a false alarm. When false alarms pile up, people stop looking, and then the detector is worthless. So before you ship, estimate how many false alerts per day each threshold will produce.
Press Play on a diagram to walk through it one step at a time.
- 1Score
z-score or isolation forest score per row
- 2Threshold
Turn scores into alert or no alert
- 3Estimate false alerts
On clean or labelled validation data
- 4Route to people
Alert volume they can actually review
- 5Collect feedback
Record true or false for each alert
- One feature at a time
- Assumes a roughly normal shape
- Easy to explain: 3 standard deviations
- Outliers inflate the mean and std
- Many features together
- No distribution assumption
- Score is harder to explain
- Needs a contamination or threshold choice
- Payment service to Detector: Send payment features1Send payment features
- 2Score below threshold: flagDetector to Detector: Score below threshold: flag
- Detector to Review queue: Create alert with score and reasons3Create alert with score and reasons
- Review queue to Analyst: Assign for review4Assign for review
- Analyst to Review queue: Mark as false alert: known customer5Mark as false alert: known customer
- Review queue to Detector: Feed label into weekly tuning6Feed label into weekly tuning
In depth
Start with synthetic anomalies
Real anomalies are rare and usually unlabelled, so you cannot measure a detector on them at first. Synthetic data fixes this. Generate a large normal population, for example two correlated Gaussian features, then inject a known number of anomalies of different kinds: point anomalies far from everything, contextual ones that are normal in value but wrong for their group, and subtle ones just outside the normal range.
Keep a column that says which rows you injected. Now you can compute recall, the share of injected anomalies caught, and the false alert rate, the share of normal rows flagged, for any method and threshold. Be honest about the limits: your detector will look excellent on obvious anomalies you invented. Include hard cases, and later validate on a small, reviewed sample of real data.
- Point anomalies: far from all normal data
- Contextual anomalies: normal value, wrong context
- Subtle anomalies: just outside normal ranges
- Always keep the ground-truth flag for evaluation
Statistical thresholds and their weak spots
A z-score is (value - mean) / standard deviation. With truly normal data, about 0.27 percent of values fall beyond 3 standard deviations, so even a perfect process will raise that many false alerts. Real data often has heavier tails, so the true rate is usually higher.
The bigger problem is masking: large outliers inflate the mean and standard deviation, which makes other outliers look normal. A robust z-score fixes this by using the median and the median absolute deviation (MAD): 0.6745 x (value - median) / MAD, with a common cut-off of 3.5. For skewed data, such as payment amounts, transform first with a log, or use percentile thresholds such as the 99.9th percentile of a clean reference period. Statistical rules are per feature, so they miss rows that are only odd in combination, like a small payment from a new country at 3am.
- Mean and standard deviation
- Cut-off about 3
- Distorted by outliers
- Median and MAD
- Cut-off about 3.5
- Resists masking
- Fixed quantile of clean history
- No shape assumption
- Needs a clean reference period
How an isolation forest scores points
An isolation forest builds many random trees. Each tree picks a random feature and a random split value, again and again, until every point in its sample sits alone. Normal points sit in crowded areas and need many splits to isolate; anomalies sit apart and are cut off in a few. The average path length across trees becomes the score.
In scikit-learn, IsolationForest defaults to n_estimators=100, max_samples="auto" (256 rows per tree, or fewer for small data) and contamination="auto". score_samples returns a value where lower means more abnormal; decision_function shifts this by an offset so that negative values are outliers; predict returns -1 for outliers and 1 for inliers. Setting contamination=0.01 simply places the threshold so that about 1 percent of the training rows are flagged. It does not discover the true rate. Scale is less critical than for distance methods, but drop ID columns and encode categories sensibly.
False alerts and feedback loops
Convert rates into daily counts before choosing a threshold. A detector with 95 percent recall and a 1 percent false alert rate sounds good, but on 100,000 normal events a day it sends 1,000 false alerts. If real anomalies are 10 a day, more than 99 percent of alerts are false. Pick the threshold from the alert budget your reviewers can handle, then check what recall that gives.
Plan for feedback from the start. Each alert should be marked true, false or unsure, with a short reason. Those labels let you measure precision over time, tune the threshold and eventually train a supervised model. Watch for bias in the loop: you only get labels for flagged rows, so missed anomalies stay invisible. Review a small random sample of unflagged rows too, and retrain on clean reference data so confirmed anomalies do not become the new normal.
- 1Detector flags rows
Within the daily alert budget
- 2Reviewer labels alerts
True, false or unsure, with a reason
- 3Sample unflagged rows
Find what the detector missed
- 4Measure precision and recall
Track them week by week
- 5Tune or retrain
Adjust threshold or features
- Back to step 1
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Generate synthetic anomalies~35m
- 2Set statistical thresholds~35m
- 3Fit an isolation forest~35m
- 4Estimate false alerts~35m
- 5Plan for alert feedback loops~35m
Key points
- Build synthetic anomalies first so you know the right answer and can measure recall and false alerts.
- A robust z-score using the median and MAD resists the outliers you are trying to find.
- IsolationForest isolates odd points in fewer random splits; predict returns -1 for outliers.
- Estimate the false alert rate per day, not just per row: 0.3 percent of a million rows is 3,000 alerts.
- Alerts that people dismiss without recording why teach you nothing; design the feedback loop up front.
Key terms
Tap a card to flip it. 0/5 known
Examples
import numpy as np
from sklearn.ensemble import IsolationForest
rng = np.random.default_rng(0)
normal = rng.normal(0, 1, size=(2000, 2))
odd = rng.uniform(-6, 6, size=(40, 2))
X = np.vstack([normal, odd]); y = np.r_[np.zeros(2000), np.ones(40)]
iso = IsolationForest(n_estimators=200, contamination=0.02, random_state=0).fit(X)
flag = iso.predict(X) == -1
print("recall", flag[y == 1].mean().round(2))
print("false alert rate", flag[y == 0].mean().round(3))Synthetic data with known anomalies lets you measure both recall and false alerts.
Masking breaks the classic z-score
Simulate 1,000 response times around 200 ms with a spread of 20 ms, then add 30 extreme values near 2,000 ms. Step 1: compute classic z-scores. The outliers stretch the standard deviation from about 20 to over 300, so most of them score under 6 and moderate anomalies near 300 ms score under 1. Step 2: compute robust z-scores with the median and MAD. The median stays near 200 and the MAD stays small, so every injected value stands out clearly. Step 3: compare both at their usual cut-offs. Both still catch the extreme values, but only the robust score would also flag a moderate anomaly such as 300 ms.
import numpy as np
rng = np.random.default_rng(0)
x = np.r_[rng.normal(200, 20, 1000), rng.normal(2000, 50, 30)]
y = np.r_[np.zeros(1000), np.ones(30)]
z = (x - x.mean()) / x.std()
med = np.median(x); mad = np.median(np.abs(x - med))
rz = 0.6745 * (x - med) / mad
for name, flag in [("z>3", np.abs(z) > 3), ("robust>3.5", np.abs(rz) > 3.5)]:
print(name, "recall", flag[y == 1].mean().round(2),
"false rate", flag[y == 0].mean().round(3))Choosing a threshold from an alert budget
A team can review 20 alerts a day and the system sees about 50,000 events a day. Step 1: the budget allows a flag rate of 20 / 50,000 = 0.04 percent. Step 2: on a clean week of history, find the isolation forest score at the 0.04th percentile; that is the threshold. Step 3: on synthetic injected anomalies, measure what recall this threshold gives. Step 4: if recall is too low, improve features rather than lowering the threshold, because a lower threshold breaks the budget.
import numpy as np
from sklearn.ensemble import IsolationForest
rng = np.random.default_rng(0)
clean = rng.normal(size=(50000, 3))
iso = IsolationForest(random_state=0).fit(clean)
budget_rate = 20 / 50000
threshold = np.quantile(iso.score_samples(clean), budget_rate)
test = np.vstack([rng.normal(size=(5000, 3)), rng.normal(5, 1, size=(20, 3))])
flag = iso.score_samples(test) < threshold
print("alerts:", flag.sum(), "caught:", flag[-20:].sum(), "of 20")Quick reference
- z = (x - mean) / std; normal data has about 0.27 percent beyond 3
- Robust z = 0.6745 x (x - median) / MAD; flag above about 3.5
- IsolationForest: predict gives -1 for outliers; lower score_samples = more abnormal
- contamination sets the flagged share; it does not measure the true anomaly rate
- Daily false alerts = false alert rate x normal events per day
- Set the threshold from the review budget, then measure recall
- Log every alert outcome and sample unflagged rows too
Common mistakes
- Leaving contamination at a guess and treating the flagged share as the true anomaly rate.
- Computing the mean and standard deviation on data full of the anomalies you want to catch.
- Shipping a detector with no owner, review queue or way to mark alerts as false.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Generate 1,000 normal values (mean 50, std 5) and 10 injected values near 90. Flag values with an absolute z-score above 3 and print recall and the false alert rate.
- Exercise 2medium
On 2D synthetic data with 2 percent injected anomalies, compare an isolation forest at contamination 0.01, 0.02 and 0.05. Report recall and false alert rate for each.
- Exercise 3hard
Design an alert policy for a login service with 400,000 normal logins a day, 5 real attacks a day and two reviewers who can each handle 25 alerts. State the threshold rule, expected precision at 80 percent recall, and the feedback process.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between outlier detection and novelty detection?
- Outlier detection assumes the training data itself contains some anomalies. Novelty detection trains on clean data only and asks whether new rows look different. scikit-learn supports both, for example LocalOutlierFactor with novelty=True.
- Does an isolation forest need scaled features?
- It is much less sensitive to scale than distance-based methods because it splits one feature at a time, but you should still remove IDs and encode categories carefully.
- When should I switch to a supervised model?
- Once you have enough reviewed alerts, including confirmed true and false ones, a classifier trained on those labels usually beats an unsupervised score. Keep the unsupervised detector to catch new kinds of anomaly.