Rare, unlabelled, and expensive to miss
A payments processor sees twenty thousand card-not-present transactions a day and employs two analysts who can review about 120 of them. Eighty of the twenty thousand are fraudulent, and nobody has labelled them. Model based anomaly detection is how you decide which 120 to send, by learning what ordinary traffic looks like and ranking every row by how badly it fits.
This is not the same problem as detecting and treating outliers column by column, which asks whether a single value is implausible and is usually handled with an interquartile range or a z-score. Fraud here is not extreme on any one field. The amount is high but not record-breaking, the billing-to-shipping distance is large but legal, the device has a few cards on it. It is the combination that is strange, and only a model that looks at all five fields together will see it.
import numpy as np, pandas as pd
rng = np.random.default_rng(11)
def draw(k, amt_mu, vel_mu, km_mu, dev_mu):
return pd.DataFrame({
"amount_gbp": np.exp(rng.normal(amt_mu, 0.8, k)).round(2),
"velocity_1h": rng.poisson(vel_mu, k),
"billing_ship_km": np.abs(rng.normal(km_mu, 40, k)).round(1),
"cards_per_device": rng.poisson(dev_mu, k) + 1,
"hour": rng.integers(0, 24, k),
})
legit = draw(19920, 3.4, 1.2, 12, 0.2)
fraud = draw(80, 4.6, 4.0, 320, 2.4)
txn = pd.concat([legit, fraud], ignore_index=True)
y = np.r_[np.zeros(19920, int), np.ones(80, int)]
order = rng.permutation(len(txn))
txn, y = txn.iloc[order].reset_index(drop=True), y[order]
print(txn.shape, round(y.mean(), 4))
# (20000, 5) 0.004
The labels exist only so you can score the detectors. No model sees y.
Three anomaly detection models you will actually use
IsolationForest grows random trees that split on random features at random thresholds, then measures how few splits it takes to isolate each row. Odd rows get isolated fast and score low. OneClassSVM fits a boundary around the bulk of the data in kernel space, with nu bounding the fraction left outside. LocalOutlierFactor compares each point’s local density with its neighbours’ density, so it can flag a point that sits in a sparse pocket even when it is nowhere near the global edge.
Rather than accuracy, score them the way the operation works: of the 120 rows you send to the analysts, how many are fraud?
from sklearn.ensemble import IsolationForest
from sklearn.svm import OneClassSVM
from sklearn.neighbors import LocalOutlierFactor
from sklearn.preprocessing import StandardScaler
X = StandardScaler().fit_transform(txn)
BUDGET = 120
def at_budget(score):
flagged = np.argsort(score)[:BUDGET] # lowest score = most anomalous
hits = y[flagged].sum()
return hits / BUDGET, hits / y.sum()
iso = IsolationForest(n_estimators=300, contamination=0.004, random_state=0).fit(X)
svm = OneClassSVM(nu=0.004, gamma="scale").fit(X)
lof = LocalOutlierFactor(n_neighbors=35, contamination=0.004)
lof.fit_predict(X)
scores = {"Isolation Forest": iso.score_samples(X),
"One-Class SVM": svm.score_samples(X),
"Local Outlier Factor": lof.negative_outlier_factor_,
"random 120": rng.normal(size=len(y))}
for name, s in scores.items():
p, r = at_budget(s)
print(name, round(p, 3), round(r, 3))
# Isolation Forest 0.658 0.988
# One-Class SVM 0.317 0.475
# Local Outlier Factor 0.075 0.112
# random 120 0.0 0.0
print(round((iso.predict(X) == np.where(y == 1, -1, 1)).mean(), 4),
round((y == 0).mean(), 4))
# 0.9994 0.996
| Detector | Precision at 120 alerts | Recall | Fraud found |
|---|---|---|---|
| Isolation Forest | 0.658 | 0.988 | 79 of 80 |
| One-Class SVM | 0.317 | 0.475 | 38 of 80 |
| Local Outlier Factor | 0.075 | 0.112 | 9 of 80 |
| Random selection | 0.000 | 0.000 | 0 of 80 |
Isolation Forest wins by a wide margin: two in three alerts are real fraud and it catches 79 of the 80 cases inside the budget. Local Outlier Factor is close to useless here, and the reason is instructive rather than embarrassing. The eighty fraudulent rows were drawn from one shifted distribution, so they form their own small dense cluster. Each fraudulent point has thirty-four other fraudulent neighbours packed around it, its local density looks perfectly normal, and LOF shrugs. LOF earns its keep on scattered one-off anomalies and loses badly to anything coordinated.
Why accuracy is the wrong metric
The last two numbers in that block are the argument. Isolation Forest’s labels are 99.94 per cent accurate. Predicting “nothing is fraud” for every row is 99.6 per cent accurate and catches nothing. Four tenths of a percentage point separates a working detector from a constant. At a 0.4 per cent base rate, accuracy cannot distinguish them, which is why precision and recall at a fixed budget is the only framing an operations team can act on. Alert capacity is a real constraint. Report your metric at it.
What contamination actually does
contamination is the single most misread parameter in scikit-learn’s outlier detection module. It does not change how the model learns. It sets the quantile at which predict draws the line between 1 and -1.
for c in (0.001, 0.004, 0.02, 0.1):
m = IsolationForest(n_estimators=300, contamination=c, random_state=0).fit(X)
print(c, int((m.predict(X) == -1).sum()),
round(at_budget(m.score_samples(X))[0], 3))
# 0.001 20 0.658
# 0.004 80 0.658
# 0.02 400 0.658
# 0.1 2000 0.658
The flagged count is exactly contamination times the row count, and precision at 120 does not budge, because the ranking is identical in all four runs. The lesson: ignore predict and work with score_samples or decision_function, then threshold where your capacity sits. You get a dial you can defend to the business instead of a guess about a rate nobody knows.
One more decision is whether to fit on data that may contain anomalies, or on a clean historical window and treat new rows as novelties.
history = X[y == 0][:15000]
nov = IsolationForest(n_estimators=300, contamination=0.004,
random_state=0).fit(history)
p, r = at_budget(nov.score_samples(X))
print(round(p, 3), round(r, 3))
# 0.608 0.912
Fitting on verified-clean history scored slightly worse, 0.608 against 0.658, which surprised me. With contamination at four in a thousand there is too little fraud to distort the trees, and the extra five thousand rows of ordinary traffic were worth more than the purity. At higher contamination the result flips, and a clean reference window becomes the better choice. Test it on your own base rate rather than assuming.
For wide data, running a decomposition first helps: scoring in the space from principal component analysis is standard practice when you have hundreds of correlated columns, and the trade-offs are worked through in the Codeayan piece on anomaly detection in high-dimensional data. scikit-learn’s outlier detection guide documents the novelty versus outlier distinction in detail.
Frequently Asked Questions
Which anomaly detection algorithm should I start with?
Isolation Forest. It needs no distance metric tuning, scales to large datasets, handles mixed feature magnitudes once scaled, and here it reached 0.658 precision at a 120-alert budget against 0.317 for One-Class SVM. Try Local Outlier Factor second, and only if your anomalies are isolated one-offs.
What value should I set for contamination?
For ranking, it does not matter. It only moves the threshold predict uses, not the scores. Set it to your real alert capacity divided by your row count if you want predict to be meaningful, or ignore predict and threshold score_samples yourself.
Should I use anomaly detection or a supervised classifier?
If you have reliable labels and enough positive cases, train a classifier: it will beat any unsupervised detector. Reach for anomaly detection when labels are absent, when fraud patterns change faster than you can label them, or as a first pass to generate cases worth labelling.
Key Takeaways
- Start with
IsolationForestfor tabular anomaly detection, and scale your features first since the others depend on distances. - Score detectors by precision at your real alert budget, because accuracy at a 0.4 per cent base rate cannot separate a working model from a constant.
- Use
score_samplesand set your own threshold, sincecontaminationchanges only wherepredictcuts and left precision at 120 unchanged across a hundredfold range. - Expect Local Outlier Factor to fail on coordinated anomalies that form their own dense cluster, as it did here at 0.075 precision.
- Test fitting on clean history against fitting on everything rather than assuming, because the clean window lost here at this base rate.