Build an Anomaly Detection System with Isolation Forest
classical-ml anomaly-detection model-evaluation mlops View full code for this problem
ML Problem & Solution
Anomaly Detection with Isolation Forest
Isolating the strange is cheaper than modelling the normal, provided you take the seasonality out first.
A payments platform serves 3,400 merchants through a card-present and card-not-present API. Things go wrong in ways nobody enumerated in advance: a merchant’s credentials leak and someone starts testing stolen cards through their account, an integration upgrade silently starts double-charging, a newly onboarded “electronics reseller” turns out to be a fraud ring laundering through refunds, a load balancer misroutes 8% of authorisation requests to a region with a stale key. The platform team has 11 metrics per merchant at 5 minute granularity and a single on-call analyst with time to look at about 50 things a day.
What exists today is a wall of static thresholds. Alert when a merchant’s decline rate exceeds 30%. Alert when request volume moves more than three standard deviations from its own mean. Alert when refund ratio exceeds 15%. It generates 4,100 alerts a day. The analyst reviews 50 of them, roughly at random, and finds something real in about one. The other 4,050 fall on the floor. Every one of the last six incidents was found by a merchant emailing support, not by the system, and two of them had been firing an alert continuously for eleven days.
The obvious instinct is to train a classifier. There is no training set. The incident tracker has 47 confirmed incidents across 14 months, they span at least six mechanically unrelated failure types, and the next incident will very likely be a seventh type that has never occurred. This is the structural difference from the fraud classifier problem: there, positives are rare but they recur, and 1,800 labelled frauds teach you what fraud looks like. Here, the defining property of what we want to catch is that it has not happened before. A supervised model would learn the six known shapes and be blind to the seventh, which is the one that will actually cost money.
The reflex fix, and the reason this problem is subtler than it looks, is to model what normal looks like and flag departures from it. That works in one dimension and degrades fast. Every metric individually can sit inside its normal range while the combination is impossible: 400 authorisation attempts per minute is normal for this merchant, a 94% approval rate is normal, an average ticket of $12 is normal, and all three at 4am on a Sunday for a merchant whose entire history is $80 daytime transactions is card testing. No per-metric threshold sees it, because no metric is individually out of range.
Isolation Forest inverts the modelling question. Instead of describing the normal region and measuring distance from it, it asks how hard each point is to separate from everything else. The analogy is twenty questions with random questions: if you are picking people out of a crowd by asking arbitrary yes-or-no questions about measurable attributes, the person who is 6 foot 11 gets uniquely identified in about three questions, while someone of median height, median age, and median income takes a dozen. Anomalies are easy to isolate because they sit in sparse regions. That is a property you can measure with random splits, and it costs nothing to estimate.
Formally: given a stream of merchant-window feature vectors x in R^d with no labels, assign each an anomaly score s(x) in (0, 1) and surface the top n per day, maximising precision at the analyst’s fixed capacity of 50 reviews per day and recall against confirmed incidents, subject to a scoring latency under 50ms per window and a model that retrains nightly on a rolling window.
Framing the Problem
This is unsupervised outlier detection on a streaming tabular feature set, with one constraint that shapes everything downstream: the output is not a decision, it is a ranked queue with a fixed length.
That framing matters because it dissolves the question everyone asks first, which is what threshold to use. There is no statistically principled threshold for “anomalous” when the class does not exist as a population. But there is an entirely principled operational threshold: the analyst can review 50 items a day, so the threshold is the 50th highest score of the day, whatever numeric value that turns out to be. The model’s job is to rank. The capacity sets the cut.
The target definition problem
There is no target, but there is something almost as important that has to be pinned down: what counts as a hit when an analyst reviews an alert. We use three outcomes, and the middle one is where most of the honesty in the project lives.
- Actionable: the analyst opened a ticket, contacted the merchant, or escalated. Counts as a true positive.
- Explained and benign: genuinely unusual, correctly surfaced, and harmless. A merchant ran a flash sale. A legitimate integration migration. These are not false positives in the modelling sense, because the model did its job, but they consume the same analyst minute as a false positive and so they count against precision in the operational metric. Tracking them separately is what tells you whether to fix the model or fix the features.
- Noise: nothing distinguishable happened. A false positive in every sense.
Constraints
- 50 alerts per day, hard. One analyst. This is the single number that determines the operating point, and no model improvement changes it.
- Scoring latency under 50ms per merchant-window, because scores feed a 5 minute batch that must finish well inside its window. 3,400 merchants per window is the real load.
- No labels at training time, and the label set that does exist is biased. The 47 confirmed incidents are the ones somebody eventually noticed, which over-represents incidents that the old threshold system could catch and incidents that merchants complain about. Recall against this set is a useful lower bound and a bad absolute measure.
- Explainability per alert. An analyst given a score of 0.71 and nothing else cannot act. Every alert needs the two or three features that drove it.
- Non-stationarity is the normal state. Merchant volumes have daily and weekly cycles, the platform onboards 40 merchants a month, and Black Friday is not an incident.
- No retraining on unreviewed data without a window. A persistent anomaly that stays in the training window long enough becomes part of the model’s notion of normal.
Precision at 50 per day, written P@50, measured on analyst dispositions. Of the 50 highest-scoring merchant-windows surfaced each day, what fraction were actionable. The baseline is 2.8%, so roughly one useful alert per day and 49 wasted reviews. Every candidate model is compared at exactly 50 alerts, never at its own preferred threshold, because comparing two detectors at different alert volumes compares nothing. ROC-AUC is actively misleading here: with 2.9M merchant-windows a month and perhaps four anomalous ones, a detector can score 0.97 ROC-AUC and still fill all 50 daily slots with noise, since the false positive rate axis is dominated by the millions of easy negatives. PR-AUC is better and still averages over operating points nobody will ever run at.
Guardrail metrics: recall against the 47 confirmed incidents (read as a lower bound), median time-to-detect from incident onset to alert, alert volume stability day over day (a detector whose natural volume swings from 12 to 900 is unusable even at good precision), and the injected-anomaly detection curve described in the evaluation section.
Out of scope: root-causing. The system ranks and explains which features drove a score. Deciding that a spike in decline_rate_5m with a flat volume_5m means a stale key in one region is an analyst’s job informed by a runbook, and no unsupervised detector will do it.
Anomaly detection projects fail at the framing step far more often than at the modelling step, and the failure has a signature: the team asks "what threshold means anomalous" instead of "how many alerts can we review". The first question has no answer, so it gets settled by picking contamination=0.01 because it looks like a reasonable prior, which silently commits the system to 29,000 alerts a month. The second question has an answer that someone in operations already knows, and it converts an unbounded statistical problem into a bounded ranking problem with a well-defined metric.
Data and Features
The raw stream is 11 metrics per merchant per 5 minute window: authorisation attempts, approvals, declines by category, refunds, chargeback notifications, average and p95 ticket size, distinct card count, distinct BIN count, unique IP count, and API error responses. 3,400 merchants times 288 windows a day is 979,200 rows a day, about 2.9M a month.
| Source | Grain | Fields used | Notes |
|---|---|---|---|
auth_events |
request | 9 | outcome, decline code, amount, BIN, latency |
refund_events |
refund | 5 | amount, original auth age, initiator |
chargeback_notices |
notice | 4 | reason code, received date, amount |
api_logs |
request | 6 | endpoint, status, client version, source IP |
merchant_dim |
merchant | 7 | MCC, onboard date, tier, expected volume band |
incident_tracker |
incident | 6 | onset, detection time, type, severity |
Rates, not counts, and this is the whole ballgame
The first version of this system ranked merchant-windows by an Isolation Forest fitted on the 11 raw metrics. It surfaced the same 30 merchants every single day: the biggest ones. That is not a bug in the model. A merchant doing 400 authorisations per minute genuinely is an outlier in the distribution of auth_count, permanently, and the model correctly reported so.
Raw counts encode merchant size, and merchant size is the dominant axis of variation in the data. Any density-based method fitted on counts spends its entire capacity rediscovering that some merchants are large. The fix is to express everything as a rate, a ratio, or a deviation from that merchant’s own baseline, so that scale drops out of the feature space entirely.
# Feature construction: 14 scale-free features per merchant-window. Nothing
# here is a raw count, and that is deliberate.
import numpy as np
import pandas as pd
EPS = 1.0 # Laplace-style smoothing: a window with 2 requests and 1 decline
# must not read as a 50% decline rate with the same confidence as
# one with 2,000 requests and 1,000 declines.
def build_window_features(w: pd.DataFrame) -> pd.DataFrame:
"""`w` is one row per merchant per 5 minute window with raw counts."""
f = pd.DataFrame(index=w.index)
attempts = w["auth_attempts"]
# Group 1: outcome composition. Ratios, smoothed.
f["decline_rate"] = (w["declines"] + EPS) / (attempts + 2 * EPS)
f["soft_decline_share"] = (w["declines_soft"] + EPS) / (w["declines"]
+ 2 * EPS)
f["api_error_rate"] = (w["api_5xx"] + EPS) / (w["api_requests"] + 2 * EPS)
f["refund_ratio"] = (w["refund_amount"] + 1.0) / (w["approved_amount"]
+ 1.0)
# Group 2: card and identity dispersion. The signature of card testing is
# many distinct cards against few distinct IPs, which no single count
# reveals.
f["cards_per_attempt"] = w["distinct_cards"] / (attempts + EPS)
f["bins_per_card"] = w["distinct_bins"] / (w["distinct_cards"] + EPS)
f["attempts_per_ip"] = attempts / (w["distinct_ips"] + EPS)
# Group 3: ticket shape, in log space because amounts are log-normal.
f["log_avg_ticket"] = np.log1p(w["approved_amount"] / (w["approvals"]
+ EPS))
f["ticket_p95_ratio"] = (w["ticket_p95"] + 1.0) / (
w["approved_amount"] / (w["approvals"] + EPS) + 1.0)
f["round_amount_share"] = (w["round_amounts"] + EPS) / (w["approvals"]
+ 2 * EPS)
# Group 4: velocity relative to the merchant's OWN recent history. This is
# what makes the feature space comparable across a merchant doing 4
# requests an hour and one doing 400 a minute.
med = w.groupby("merchant_id")["auth_attempts"].transform(
lambda s: s.rolling(288 * 7, min_periods=288).median())
f["volume_ratio_7d"] = (attempts + EPS) / (med + EPS)
f["latency_ratio_7d"] = w["p95_latency_ms"] / (
w.groupby("merchant_id")["p95_latency_ms"].transform(
lambda s: s.rolling(288 * 7, min_periods=288).median()) + EPS)
# Group 5: burstiness within the window.
f["attempt_gini"] = w["attempt_gini"]
f["retry_share"] = (w["retried_attempts"] + EPS) / (attempts + 2 * EPS)
return f
Deseasonalise, or 2am is permanently anomalous
An Isolation Forest has no notion of time. Feed it volume_ratio_7d computed against a flat median and every window between midnight and 5am scores as anomalous for every merchant, because volume genuinely is 40 times lower then. Roughly 20% of all windows are overnight, so a detector that thinks overnight is strange will fill its 50 daily slots before breakfast.
The fix is to residualise against a seasonal baseline before scoring. A full STL decomposition per merchant per metric is overkill at this granularity and does not survive the sparse overnight windows. A day-of-week by hour-of-day median, computed per merchant over a trailing 8 weeks with a global fallback for thin cells, handles it and costs almost nothing.
# Seasonal residualisation. Score the residual, never the raw rate.
# Without this step, 20% of all windows are structurally anomalous and the
# alert queue is permanently full of 3am.
SEASONAL = ["volume_ratio_7d", "decline_rate", "api_error_rate",
"attempts_per_ip", "latency_ratio_7d"]
def fit_seasonal_baseline(feat: pd.DataFrame, ts: pd.Series,
merchant: pd.Series,
min_cell: int = 6) -> pd.DataFrame:
keys = pd.DataFrame({"merchant_id": merchant,
"dow": ts.dt.dayofweek,
"hour": ts.dt.hour})
grouped = feat[SEASONAL].groupby(
[keys["merchant_id"], keys["dow"], keys["hour"]])
base = grouped.median()
counts = grouped.size().rename("n")
# Cells with too few observations borrow from the platform-wide pattern
# for that day and hour. A newly onboarded merchant has no history of its
# own Tuesday 3am, and imputing the merchant's overall median there would
# make every off-peak window look like a spike.
glob = feat[SEASONAL].groupby([keys["dow"], keys["hour"]]).median()
thin = counts[counts < min_cell].index
for idx in thin:
base.loc[idx] = glob.loc[(idx[1], idx[2])]
return base
def residualise(feat: pd.DataFrame, base: pd.DataFrame, ts: pd.Series,
merchant: pd.Series) -> pd.DataFrame:
out = feat.copy()
key = pd.MultiIndex.from_arrays([merchant, ts.dt.dayofweek, ts.dt.hour])
expected = base.reindex(key)
for c in SEASONAL:
e = expected[c].to_numpy()
# Log ratio rather than difference: these are rates and ratios, so a
# doubling should read the same whether the baseline is 0.02 or 0.4.
out[c] = np.log((feat[c].to_numpy() + 1e-3) / (e + 1e-3))
return out
The contamination that matters here is training on incidents
Leakage in the classical sense needs a label, and there is none. Two analogous contaminations bite instead.
The training window absorbs the anomaly. If the model retrains nightly on the trailing 30 days and a merchant has been double-charging for three weeks, that behaviour is now 21 days of training data and the model has learned it is normal. Real measured effect: a duplicate-charge incident scored 0.79 on day one, 0.71 on day seven, and 0.58 on day nineteen, dropping out of the top 50 on day nine while still actively costing money. The mitigation is to exclude windows that were previously alerted and confirmed actionable from subsequent training sets, which requires the feedback loop to exist before the model ships.
Evaluating on the incidents the old system found. The 47 confirmed incidents are not a random sample of incidents. They are the ones that got noticed, which is heavily weighted toward large merchants, toward failure modes the threshold system could see, and toward anything a merchant would phone in about. Reporting recall against this set as though it were recall against all incidents overstates performance on exactly the class of subtle, small-merchant events the new system is meant to catch. We report it, label it a lower bound, and lean on injected synthetic anomalies for the sensitivity curve.
One-hot encoding merchant_id into the feature matrix. It seems reasonable: the model should know which merchant it is looking at. What actually happens is that the feature space gains 3,400 near-orthogonal binary columns, every merchant becomes unique by construction, and because Isolation Forest splits on one randomly chosen feature at a time, most splits land on a dummy column that separates one merchant from the other 3,399 in a single cut. Average path lengths collapse, every point looks isolated, and the score distribution flattens into noise. Merchant identity belongs in the features as a relative quantity: the ratio to that merchant's own rolling median, which is what volume_ratio_7d is. The same argument applies to high-cardinality MCC codes and to raw timestamps.
The Naive Baseline
The incumbent is per-metric static and 3-sigma thresholds. It deserves a real implementation because its failure is specific and instructive.
# The incumbent: independent per-metric 3-sigma bands on a 7 day rolling
# window, plus three hard business thresholds.
import numpy as np
import pandas as pd
HARD = {"decline_rate": 0.30, "refund_ratio": 0.15, "api_error_rate": 0.05}
def sigma_baseline(feat: pd.DataFrame, merchant: pd.Series,
n_sigma: float = 3.0) -> pd.Series:
flags = pd.Series(False, index=feat.index)
for c, limit in HARD.items():
flags |= feat[c] > limit
for c in feat.columns:
g = feat.groupby(merchant)[c]
mu = g.transform(lambda s: s.rolling(288 * 7, min_periods=288).mean())
sd = g.transform(lambda s: s.rolling(288 * 7, min_periods=288).std())
flags |= (feat[c] - mu).abs() > n_sigma * sd
return flags
Measured over 14 months of replay: 4,100 alerts per day, P@50 of 2.8%, and 21 of the 47 confirmed incidents caught, at a median time-to-detect of 47 minutes among those caught. It fails in four distinct ways, and only the first is about volume.
It cannot see joint anomalies. Each metric is tested alone, so the card testing signature (normal volume, normal approval rate, normal ticket, all three impossible together at 4am for that merchant) produces no flag on any axis.
Three sigma is the wrong tail model. These features are not Gaussian. decline_rate is bounded and skewed, attempts_per_ip is heavy-tailed. The mean and standard deviation of a heavy-tailed variable are themselves unstable, and a single large spike inflates the rolling standard deviation enough that the band widens and the next spike passes unflagged. This is why two incidents alerted for eleven days and then silently stopped.
No multiplicity correction. 14 metrics times 3,400 merchants times 288 windows is 13.7M independent tests a day. At a nominal 0.27% two-sided rate for a 3-sigma band, pure chance produces roughly 37,000 flags a day even if nothing is wrong. Deduplication down to merchant-day brings it to 4,100, which is the number we see.
Alerting on a state rather than a change. A merchant whose business model genuinely runs a 34% decline rate trips the hard threshold every window forever. 61% of the 4,100 daily alerts come from 190 merchants who have been alerting continuously for more than 30 days.
A simple multivariate upgrade, Mahalanobis distance on the 14 features against a per-merchant covariance, is worth a number too: P@50 of 7.1% and 24 of 47 incidents. Better, because it at least sees correlations, and still poor, because it assumes one elliptical normal region and most merchants have several legitimate modes.
The Solution
Isolation Forest, from Liu, Ting and Zhou’s 2008 ICDM paper, starts from an observation that sounds too simple to work: anomalies are few and different, so they are easy to separate with random cuts.
Build a tree by picking a feature at random and a split value at random between that feature’s min and max in the current node, then recurse until every point is isolated or a depth limit is hit. Record the depth at which each point ended up alone. A point in a sparse region gets cut off from the crowd after a couple of splits. A point in the dense middle needs many. Average that depth over a few hundred independently random trees and you have a robust estimate of how isolated the point is, with no distance metric, no density estimate, and no assumption about the shape of the normal region.
The scoring formula normalises path length against what you would expect from an unsuccessful search in a binary search tree, which is how the raw depths become a comparable score:
c(n) = 2 * H(n - 1) - 2 * (n - 1) / n where H(i) is the ith harmonic number
s(x,n) = 2 ^ ( - E[h(x)] / c(n) )
E[h(x)] is the mean path length across trees, c(n) is the expected path length for a random point given n samples. Scores near 1 mean much shallower than expected, so anomalous. Scores near 0.5 mean indistinguishable from typical. Scores well below 0.5 mean the point is in an unusually dense region, which is occasionally interesting in its own right.
Why this beats the alternatives on this problem
Against Mahalanobis or a multivariate Gaussian: no assumption of a single elliptical mode. Merchants have several legitimate operating modes (weekday retail, weekend spike, batch settlement) and a unimodal model treats the gap between modes as normal and the modes themselves as marginal.
Against Local Outlier Factor: LOF is genuinely good at local density anomalies and is O(n^2) without an index, needs the whole reference set at scoring time, and gives no compact model to ship. On 2.9M rows a month it was 9 minutes per scoring batch against 0.14 seconds.
Against an autoencoder: reconstruction error is a reasonable anomaly score and the model needs tuning, a GPU for comfort, and careful early stopping, and it buys nothing on 14 tabular features. It becomes the right answer when the input is a sequence or an image.
The hyperparameters that matter
# The core model. Three parameters carry almost all of the behaviour, and the
# defaults are right for two of them.
from sklearn.ensemble import IsolationForest
iforest = IsolationForest(
# 200 trees. Detection performance plateaus around 100 to 200 in the
# original paper; more trees buy score STABILITY between nightly refits,
# which matters because the alert cut is a rank threshold.
n_estimators=200,
# 256 is not a default to be tuned away. Liu et al. show detection
# converges by 256 subsamples, and the small sample is what defeats
# masking and swamping: a tree that only ever sees 256 points cannot have
# its splits dominated by a cluster of 4,000 anomalous windows, and dense
# normal regions near an anomaly do not get dragged into a shallow branch.
max_samples=256,
# All 14 features per tree. Feature subsampling helps in hundreds of
# dimensions and only adds variance at 14.
max_features=1.0,
# contamination sets sklearn's internal `offset_` for predict() and
# decision_function(). We never use those: the threshold comes from the
# analyst budget. Setting it explicitly avoids the "auto" offset quietly
# changing between sklearn versions.
contamination=0.01,
n_jobs=-1,
random_state=11,
).fit(X_train)
# score_samples returns NEGATIVE anomaly score, higher meaning more normal.
# Flip it so larger is more anomalous, which is what everything downstream
# assumes.
scores = -iforest.score_samples(X_score)
max_samples is the parameter people tune first and should tune last. Raising it to 4,096 on this data dropped P@50 from 34% to 26%, because the larger subsample lets a persistent cluster of anomalous windows appear often enough in each tree to build its own dense region and hide inside it. That is masking, and the 256 default is the paper’s answer to it.
The threshold comes from the budget, not from the model
# The alert cut. Note that the quantile is computed on a TRAILING score
# distribution rather than today's, so a genuinely quiet day surfaces fewer
# than 50 alerts instead of scraping the bottom of the barrel to fill the
# queue.
import numpy as np
def alert_threshold(trailing_scores: np.ndarray, budget_per_day: int = 50,
windows_per_day: int = 979_200) -> float:
q = 1.0 - (budget_per_day / windows_per_day)
return float(np.quantile(trailing_scores, q))
def select_alerts(scores, threshold, merchant_ids, budget=50):
hit = np.flatnonzero(scores >= threshold)
order = hit[np.argsort(scores[hit])[::-1]]
# Deduplicate to one alert per merchant per day. Without this, a single
# sustained incident consumes the entire budget with 288 copies of
# itself, which is how the incumbent system spent 61% of its alerts.
seen, out = set(), []
for i in order:
m = merchant_ids[i]
if m in seen:
continue
seen.add(m)
out.append(i)
if len(out) >= budget:
break
return np.array(out)
Explaining each alert
An analyst needs to know why. Isolation Forest has no coefficients, but a cheap and faithful attribution is available: score the window, then rescore it 14 times with one feature at a time replaced by that feature’s median, and report the features whose replacement drops the score most.
# Per-alert attribution by single-feature ablation. 14 extra scorings per
# alert at 50 alerts a day is free, and it is what turns a 0.71 into
# "attempts_per_ip and cards_per_attempt, both far above this merchant's
# baseline".
def explain(model, x, medians, feature_names, top=3):
base = -model.score_samples(x.reshape(1, -1))[0]
drops = []
for j, name in enumerate(feature_names):
probe = x.copy()
probe[j] = medians[j]
s = -model.score_samples(probe.reshape(1, -1))[0]
drops.append((name, round(float(base - s), 4)))
return sorted(drops, key=lambda t: -t[1])[:top]
The design decision that mattered most was not the algorithm and not max_samples. It was making every feature scale-free, so that merchant size stopped being the dominant axis of variation. On raw counts, P@50 was 4.1% and the model surfaced the same 30 large merchants daily. The identical Isolation Forest on rate and own-baseline-ratio features scored 34%. Isolation Forest finds whatever is sparse in the space you give it, and if merchant size is the biggest thing in that space, "this merchant is large" is the anomaly it will faithfully report every single day.
Evaluation and Metrics
Evaluating an unsupervised detector with no labels sounds impossible and is merely awkward. Four measurements together give a defensible picture, and none of them alone does.
1. Precision at the alert budget, from analyst dispositions. The primary metric. It requires the analyst to record an outcome per alert, which is a process commitment, not a modelling one, and without it the project has no metric at all. Measured at exactly 50 alerts per day for every candidate.
2. Recall against confirmed incidents. Replay historical telemetry, check whether each of the 47 incidents would have been in the top 50 on its onset day. Reported as a lower bound because the incident set is biased toward what the old system caught.
3. Injected synthetic anomalies, which is the only unbiased sensitivity measure available. Take real normal windows, inject a known perturbation of known magnitude, and measure the detection rate as a function of magnitude. This gives a sensitivity curve rather than a single number, and it is the only measurement that tells you what the system cannot see.
# Injection harness. Perturb real normal windows by a known multiplier and
# measure detection rate at the live alert threshold. The point of the curve
# is the left end: how small an anomaly slips through.
import numpy as np
INJECTIONS = {
"card_testing": {"cards_per_attempt": 6.0, "attempts_per_ip": 8.0,
"log_avg_ticket": 0.35},
"decline_spike": {"decline_rate": 4.0, "soft_decline_share": 1.8},
"duplicate_charge": {"volume_ratio_7d": 2.0, "round_amount_share": 1.4},
"refund_abuse": {"refund_ratio": 7.0, "ticket_p95_ratio": 1.3},
"integration_error": {"api_error_rate": 12.0, "latency_ratio_7d": 3.0},
}
def injection_curve(model, X_normal, feature_names, threshold,
magnitudes=(0.25, 0.5, 1.0, 2.0), n=400, seed=11):
rng = np.random.default_rng(seed)
cols = {n_: i for i, n_ in enumerate(feature_names)}
rows = []
for name, spec in INJECTIONS.items():
for m in magnitudes:
idx = rng.choice(len(X_normal), n, replace=False)
Xi = X_normal[idx].copy()
for col, mult in spec.items():
# Interpolate the multiplier toward 1.0 by magnitude, so
# m=0.25 is a quarter-strength version of the same anomaly.
Xi[:, cols[col]] *= 1.0 + (mult - 1.0) * m
det = float((-model.score_samples(Xi) >= threshold).mean())
rows.append({"anomaly": name, "magnitude": m,
"detection_rate": round(det, 4)})
return rows
4. Alert volume stability. The standard deviation of daily alert count at a fixed threshold. A detector that naturally produces 12 alerts one day and 900 the next is unusable even at excellent precision, because the analyst queue is a fixed-capacity resource.
Baseline versus solution
| Metric | 3-sigma thresholds | Mahalanobis | iForest on raw counts | iForest on deseasonalised rates |
|---|---|---|---|---|
| Alerts per day | 4,100 | 340 | 50 | 50 |
P@50 (analyst-confirmed actionable) |
2.8% | 7.1% | 4.1% | 34.0% |
| Recall on 47 confirmed incidents | 21 | 24 | 19 | 33 |
| Median time-to-detect | 47 min | 35 min | 40 min | 8 min |
| Injected detection at magnitude 0.5 | 0.19 | 0.31 | 0.22 | 0.68 |
| Distinct merchants in top 50 | 11 | 19 | 30 | 44 |
| Scoring time, 3,400 windows | 0.02 s | 0.05 s | 0.14 s | 0.14 s |
| PR-AUC on the confirmed incident set | 0.021 | 0.058 | 0.034 | 0.211 |
The “distinct merchants in top 50” row is the one that convinced the operations team, and it is not a standard metric. The raw-count model put 30 merchants in 50 slots and they were the same 30 every day. The final model puts 44 distinct merchants in 50 slots, which means the queue is actually turning over.
Note what ROC-AUC would have said. The 3-sigma baseline scores 0.981 and the final model scores 0.994. Both look excellent and the difference looks marginal, because 2.9M easy negatives dominate the false positive rate axis. The same comparison in P@50 is 2.8% against 34%, a twelvefold difference in the only quantity the analyst experiences.
The signal that catches silent degradation is the injected-anomaly detection rate at fixed magnitude, re-run nightly against the freshly retrained model. Precision from analyst dispositions has a multi-day lag and a small sample (50 a day), so a model that has quietly gone blind to one anomaly type takes two weeks to show up there, if it shows up at all. Injection is synthetic, instant, and directly measures sensitivity per anomaly type: when the duplicate-charge detection rate at magnitude 1.0 fell from 0.91 to 0.44 over nine nights, that was the retraining window absorbing an ongoing incident, and nothing else in the monitoring stack noticed.
Common Pitfalls and Failure Modes
| Pitfall | Why It Happens | How to Detect | How to Fix |
|---|---|---|---|
| Same large merchants alert daily | Raw counts encode merchant size, the dominant axis of variation | Distinct merchants in top 50 far below 50; alerts correlate with volume rank | Express every feature as a rate, ratio, or deviation from the merchant’s own rolling baseline |
| Overnight windows permanently anomalous | Isolation Forest has no time awareness; off-peak volume genuinely differs | Alert timestamps cluster between midnight and 5am | Residualise against a per-merchant day-of-week by hour-of-day baseline before scoring |
contamination used as a threshold |
It looks like a prior on anomaly rate, so it gets set from a guess | Alert volume is a fixed fraction of traffic and unrelated to review capacity | Ignore predict(); take the top n by score where n is the analyst budget |
| Ongoing incident absorbed into normal | Nightly retraining on a trailing window includes the anomaly | Score for a known active incident decays night over night | Exclude confirmed-actionable windows from training sets; monitor the injection curve |
| Masking: a cluster of anomalies hides | Large max_samples lets the anomalous cluster form its own dense region |
Detection worsens as max_samples rises |
Keep max_samples=256; it is the paper’s answer, not a default to tune away |
| Blind to rotated or correlated anomalies | Axis-parallel splits leave low-score rectangular regions where no data exists | Injected anomalies along a diagonal of two correlated features go undetected | PCA-rotate the feature space, or use Extended Isolation Forest with hyperplane splits |
| High-cardinality ID one-hot encoded | Reasonable instinct that the model should know the merchant | Score distribution flattens; mean path length collapses | Encode identity as a relative quantity, never as a dummy column |
| Sustained incident floods the queue | One incident produces 288 windows a day, all scoring high | One merchant occupies most of the top 50 | Deduplicate to one alert per merchant per day; suppress re-alerting on an open ticket |
The mistake almost everyone makes on their first Isolation Forest is calling predict() and treating the -1 labels as the answer. predict() thresholds the score using an internal offset_ derived from contamination, so what looks like the model's judgement is actually a number you guessed, applied to a score distribution you have not inspected. The default contamination="auto" makes it worse by being version-dependent and by having no relationship to your operational capacity. At 2.9M windows a month, contamination=0.01 commits you to 29,000 alerts against a review capacity of 1,500. Use score_samples(), look at the score distribution, and cut it where your staffing says to cut it.
Scaling and Productionizing
The compute is small. What makes this hard in production is the feedback loop and the fact that the model’s notion of normal is a moving target that the model itself can be fooled into moving.
Cost envelope
Feature build: 979,200 rows/day, 14 features -> 3.5 min/day, Spark
Seasonal baseline: 3,400 merchants x 168 cells -> 40 s, refit weekly
iForest fit: 200 trees x 256 samples -> 1.9 s on 2M rows
Scoring: 3,400 windows x 14 features -> 0.14 s per 5 min window
Explanation: 14 ablations x 50 alerts -> 0.6 s per day
Model artefact: 200 trees, depth <= 8 -> 2.1 MB pickled
Nightly retrain: 30 day rolling window -> under 4 min end to end
Scoring cost is 0.04ms per row and the 50ms budget is never approached. The 200 trees are the reason the artefact is 2.1 MB rather than 40 KB, and the trade is worth it because score stability between nightly refits determines whether the rank cut is stable.
The feedback loop is the system
Everything above is a ranking function. What makes it improve rather than decay is three pieces of plumbing that have nothing to do with the model:
- Disposition capture. Every alert gets one of the three outcomes from the framing section. Without this there is no
P@50and no way to tell a model regression from a quiet week. - Confirmed-actionable exclusion. Windows from confirmed incidents are removed from subsequent training windows. This is what stops an ongoing incident becoming the new normal, and it is the single most important operational rule in the system.
- Suppression with an expiry. An open ticket suppresses further alerts for that merchant and metric group, with a hard expiry (72 hours here) so that a forgotten ticket does not create a permanent blind spot. The incumbent system’s eleven-day silent alert was the inverse failure: alerting forever with nobody listening.
Monitoring
- Injection curve per anomaly type, nightly. The earliest and most specific signal, and the only one that measures sensitivity directly.
- Score distribution drift, comparing tonight’s score quantiles against a 14 day reference by KS statistic. Catches a feature pipeline break before the analyst feels it.
- Alert volume at the fixed threshold. Should be near 50 with a standard deviation under 10. A collapse to 5 means the threshold has drifted relative to the score distribution and a whole day went unwatched.
- Distinct merchants in the top 50. The cheapest single check that the model has not regressed into surfacing the same handful of accounts.
- Median time-to-detect on confirmed incidents, as a trailing 90 day figure.
The failure none of these catches is a genuine platform change that makes the previous normal obsolete: a new API version, a pricing change, a large merchant migration. The score distribution shifts, alert volume spikes, and every signal fires at once, which is correct but uninformative. The operational answer is a change calendar that the on-call reads before triaging, so a flood of alerts on the morning after a deploy is interpreted rather than investigated merchant by merchant.
Amazon's Random Cut Forest (Guha, Mishra, Roy and Schrijvers, ICML 2016) is the streaming descendant of exactly this algorithm and it ships inside Kinesis Data Analytics, OpenSearch anomaly detection, and SageMaker. It keeps the random-cut idea and replaces the uniform feature choice with a choice weighted by each dimension's range, which repairs part of the axis-parallel bias, and it supports incremental insert and delete so the forest tracks a sliding window without a nightly refit. On the research side, Extended Isolation Forest (Hariri, Carrasco Kind and Brunner, 2019) attacks the same bias directly by splitting on random hyperplanes instead of axis-parallel cuts, which removes the rectangular low-score ghost regions that plain iForest leaves behind. Both are worth knowing about specifically because they fix the one structural weakness of the model in this post.
The Isolation Forest is the cheapest and least interesting component of a working anomaly detection system. It fits in 1.9 seconds and pickles to 2.1 MB. The disposition capture, the confirmed-actionable exclusion from training, the per-merchant deduplication, the suppression expiry, and the nightly injection curve are what determine whether the system is still useful in month six. Teams that ship the model and skip the loop get a detector that works beautifully for three weeks and then quietly learns to accept whatever is currently going wrong.
Alternative Approaches
| Approach | Detection quality here | Cost at 2.9M rows/month | Interpretability | Best-fit scenario |
|---|---|---|---|---|
| Per-metric 3-sigma | Poor: P@50 2.8%, blind to joint anomalies |
Trivial | Highest: one number per metric | A handful of metrics with genuine hard limits |
| Mahalanobis / multivariate Gaussian | Weak: P@50 7.1%, assumes one elliptical mode |
Cheap, O(d^2) per point |
High: per-feature contribution is exact | Low dimensional, genuinely unimodal, roughly Gaussian data |
| Isolation Forest | Good: P@50 34%, no distributional assumption |
1.9 s fit, 0.04 ms/row | Medium: needs ablation for attribution | Default for tabular unsupervised detection, and the right first attempt |
| Extended Isolation Forest | Marginally better: P@50 36%, no blind spots |
About 1.4x iForest | Medium, same as iForest | When injected diagonal anomalies are provably missed |
| Local Outlier Factor | Comparable: P@50 31%, strong on local density |
9 min per batch, needs the reference set at scoring time | Low: no model, no global score scale | Small batch datasets with strongly varying local density |
| One-Class SVM (RBF) | Weak: P@50 12%, very sensitive to nu and gamma |
O(n^2) fit, hours |
Low | Small, clean, well-scaled datasets |
| Autoencoder reconstruction error | Comparable: P@50 33%, needs tuning and a GPU |
40 min GPU fit | Lowest | Sequences, images, or hundreds of correlated features |
| Supervised gradient boosting | Best where labels exist: 0.71 PR-AUC on the 6 known types | 2 min fit | High with SHAP | Once you have thousands of labels and the failure modes recur |
Isolation Forest is the right first choice and it stays the right choice here. Extended Isolation Forest is the upgrade to reach for, and the honest reason we have not switched is that the injection curve does not currently show a diagonal blind spot large enough to justify leaving scikit-learn, though it would be the first thing to try if one appeared.
The genuinely interesting migration is the last row. After 18 months of disposition capture the system will have accumulated several thousand labelled alerts across the recurring failure types, at which point a supervised model trained on those types will outperform the unsupervised detector on them by a wide margin. The right architecture then is not a replacement but both: a supervised model handling the known catalogue with high precision, and the Isolation Forest kept running alongside it specifically to catch the type that is not in the catalogue yet. That is the division of labour Stripe Radar-style systems converge on, and the unsupervised half never gets retired, because the whole reason it exists is the failure mode nobody has seen.
Key Takeaways
- Isolate, do not model. Isolation Forest scores how easily a point is separated by random cuts rather than how far it sits from an estimated normal region, which is why it needs no distributional assumption and costs 0.04ms per row.
- The budget is the threshold. With no label there is no principled statistical cutoff, but there is a principled operational one: the analyst’s daily review capacity. This converts an unbounded problem into a ranking problem with a real metric.
- Scale-free features or nothing. Raw counts encode merchant size, so a detector fitted on them reports “this merchant is large” forever. Rates, ratios, and deviations from a merchant’s own baseline took
P@50from 4.1% to 34% with no model change. - Deseasonalise before scoring. The model has no notion of time, so without residualising against a day-of-week by hour-of-day baseline, 20% of all windows are structurally anomalous and the queue fills with 3am.
max_samples=256is load-bearing. The small subsample is what defeats masking and swamping. Raising it to 4,096 cost 8 points ofP@50.- Never ship
predict(). It thresholds oncontamination, which is a guess you made, not a property of the data. Usescore_samples()and cut on capacity. - The training window will eat your incident. An ongoing anomaly left in the nightly retrain window becomes normal within about two weeks. Excluding confirmed-actionable windows is the single most important operational rule.
- Recall against your incident log is a lower bound, not a measurement. That log contains what somebody eventually noticed, which is biased toward what the old system could see. Injected synthetic anomalies are the only unbiased sensitivity measure available.
The counter-intuitive lesson is that ROC-AUC says this project was barely worth doing. The baseline scores 0.981 and the shipped model 0.994, a difference a stakeholder would reasonably call noise. The same comparison at the operating point anyone actually experiences is 2.8% against 34%. With 2.9M easy negatives, the false positive rate axis is almost entirely consumed by windows no method would ever flag, so ROC-AUC spends its resolution on the part of the problem that does not exist. In extreme-imbalance detection, a metric evaluated anywhere other than your real operating point is not a conservative estimate. It is a different question with a misleadingly familiar name.
Frequently Asked Questions
Q: Why not use a supervised classifier? You have 47 labelled incidents.
A: Forty-seven examples spanning at least six mechanically unrelated failure types is roughly eight per class, which will not train anything, and the deeper problem is the objective. The next incident is likely to be a type that has never occurred, and a supervised model is specifically a machine for recognising things it has seen. The right sequencing is unsupervised first to generate labelled dispositions, then supervised for the recurring catalogue once there are thousands, with the unsupervised detector kept running permanently for the unknown type.
Q: Why not just use a well-tuned multivariate Gaussian, or Mahalanobis distance? It is simpler and gives exact per-feature contributions.
A: It assumes one elliptical mode and most merchants have several legitimate ones: weekday retail, weekend spike, nightly batch settlement. A unimodal fit treats the low-density gap between modes as ordinary and the modes themselves as marginal. It scored P@50 7.1% against 34%, and the 7.1% is still a real improvement on per-metric thresholds because it at least sees correlations. If your data genuinely has one mode and 5 dimensions, Mahalanobis is the better choice and the exact attribution is worth a lot.
Q: Why is Isolation Forest better than Local Outlier Factor here, given LOF is designed for exactly this?
A: On quality they are close, 34% against 31%, and LOF is arguably the better model of the phenomenon because merchant behaviour does have strongly varying local density. It lost on operations. LOF has no compact fitted model: scoring requires the reference set, which made a batch 9 minutes instead of 0.14 seconds, and it gives no globally comparable score, so the trailing-quantile threshold that makes the alert budget work has nothing to attach to.
Q: What is wrong with contamination, and what should it be set to?
A: It is not an estimate of anything in your data, it is the parameter that sets the internal offset for predict() and decision_function(). Setting it to 0.01 because anomalies feel like about 1% commits you to 29,000 alerts a month against a capacity of 1,500. Set it explicitly to any fixed value to avoid "auto" shifting between library versions, then ignore predict() entirely and threshold score_samples() on your review capacity.
Q: Which metric would you put on the dashboard, and why not AUC?
A: P@50 from analyst dispositions as the headline, and the nightly injected-anomaly detection curve as the leading indicator. ROC-AUC is unusable at this imbalance: it reads 0.981 for a baseline with 2.8% precision and 0.994 for the shipped model at 34%, because millions of trivially normal windows dominate the false positive rate axis. PR-AUC is honest but averages over operating points that will never be run. The alert budget is fixed, so the metric should be evaluated at exactly that point.
Q: What degrades first in production, and how would you know before the analyst does?
A: The model learning to accept an ongoing incident. A duplicate-charge incident scored 0.79 on day one and 0.58 on day nineteen as the nightly retrain absorbed it, dropping out of the top 50 while still costing money. Analyst-disposition precision has a multi-day lag and a 50-per-day sample, so it will not show this. The nightly injection curve will, because detection rate for that specific anomaly type at fixed magnitude falls night over night. That plus excluding confirmed-actionable windows from training is the defence.
Interview Questions
Q: Explain how Isolation Forest assigns a score, and why anomalies get short path lengths.
Expected depth: Random feature, random split value within the node’s range, recurse to isolation or a depth cap; average path length E[h(x)] across trees; normalisation by c(n) = 2H(n-1) - 2(n-1)/n, the expected unsuccessful search length in a binary search tree; score s(x,n) = 2^(-E[h(x)]/c(n)) mapping to (0,1) with values above 0.5 meaning anomalous. The mechanism is that sparse regions get partitioned away in few cuts. Strong answers note it estimates a notion of isolation rather than density, needs no distance metric, and is O(n log n) to fit.
Q: Why is the default max_samples=256 and what happens if you raise it to 10,000?
Expected depth: Small subsamples are the paper’s defence against masking (a cluster of anomalies becoming dense enough to form its own normal region) and swamping (normal points near anomalies being pulled into shallow branches). Detection performance converges by 256, so larger subsamples add cost and reintroduce both failures. Best answers give the direction of the effect concretely: on a dataset with a persistent anomalous cluster, precision at a fixed alert budget falls as max_samples rises, which is the opposite of the usual more-data intuition.
Q: Your Isolation Forest flags the same five largest customers every day. What is wrong?
Expected depth: The features are raw counts, so scale is the dominant axis of variation and being large genuinely is being an outlier. Fix by making every feature scale-free: rates, ratios, and deviations from each entity’s own rolling baseline. Strong answers extend the same diagnosis to one-hot encoded high-cardinality IDs (path lengths collapse because a single split separates one entity from all others) and to missing seasonal residualisation, and name a diagnostic: count distinct entities in the top n, which should be close to n.
Q: There are no labels. How do you convince a stakeholder the detector works, and how do you monitor it?
Expected depth: Four independent measurements. Precision at the fixed alert budget from captured analyst dispositions, requiring a disposition process. Recall against the historical incident log, explicitly framed as a lower bound because that log is biased toward what the previous system could detect. Injected synthetic anomalies at known magnitudes for an unbiased per-type sensitivity curve. Alert volume stability at a fixed threshold. For monitoring, the injection curve nightly as the leading indicator, because disposition precision has a lag and a tiny daily sample.
Q: What is Isolation Forest structurally blind to, and how would you fix it?
Expected depth: Axis-parallel splits, which produce rectangular low-score ghost regions where no training data exists, so anomalies along a diagonal of two correlated features can score as normal. Fixes: rotate the space with PCA before fitting, or use Extended Isolation Forest (Hariri et al., 2019) with random hyperplane splits, or Random Cut Forest (Guha et al., 2016) which weights the dimension choice by range. Strong answers add the other blind spots: no time awareness, so seasonality must be removed beforehand; no notion of local density, which is where LOF wins; and no mechanism to prevent a persistent anomaly in the training window from becoming normal.
View full code for this problem