Last updated: December 3, 2026 · Formulas and defaults checked against the original papers and the scikit-learn 1.9.1 documentation on 3 December 2026. Experiments: DTF calculations on a synthetic dataset (calc.py, fixed seed).
Isolation Forest is an unsupervised anomaly detection algorithm (Liu, Ting and Zhou, 2008). It isolates each point with random splits. Anomalies are few and different, so they get cut off after fewer splits. The average path length E[h(x)] over about 100 random trees becomes the anomaly score s = 2−E[h(x)]/c(n). A score near 1 marks an anomaly. Scores well below 0.5 mean normal points. If every point scores about 0.5, there are no clear anomalies.
We fed 20,000 card transactions into an Isolation Forest with every setting left at its default. It flagged 2,474 of them. Only 150 were fraud, because we planted them ourselves in a synthetic dataset built to look like a day of card traffic. scikit-learn’s own IsolationForest gave almost the same answer: 2,678 alerts. If your fraud team can review 150 cases a day, that model just buried them.
Was the model bad? No. Of the 150 rows it ranked most suspicious, 106 were planted frauds. The problem was one parameter most tutorials skip past, plus a threshold from 2008 that was never meant as a fraud cut-off. If you are building the wider pipeline, our guide to machine learning for fraud detection shows where an unsupervised layer like this fits next to supervised models.
How does Isolation Forest work?
Most anomaly detectors model “normal” and measure distance from it. Fei Tony Liu and Kai Ming Ting at Monash University and Zhi-Hua Zhou at Nanjing University turned that around in their 2008 ICDM paper: don’t model normal at all, just try to isolate every point and count how hard it is. One isolation tree (iTree) is built like this:
- Take a random subsample of the data (256 rows by default).
- Pick a feature at random, then a split value uniformly at random between that feature’s minimum and maximum in the current node.
- Send rows below the value left and the rest right, and repeat in each branch. Stop when a node holds one row, its rows are identical, or the tree reaches its height limit of ceiling(log2 256) = 8.
The path length h(x) is the number of edges from the root to the leaf where x lands. No split is optimised and no labels are used, which is why it is fast and works on data nobody has labelled yet.
Why do anomalies isolate faster? Because, in the paper’s phrase, they are “few and different”. A transaction for $8,000 at 3 a.m. from 2,000 km away sits at the edge of several features at once, so a random cut has a fair chance of slicing it off early. A $35 lunch payment sits among thousands of near-copies and needs many cuts. In the paper’s 135-point Gaussian example, average path lengths over 1,000 trees converged to 4.02 for an outlier and 12.82 for a normal point.
The anomaly score formula, worked through
Raw path lengths grow with sample size, so the authors normalise them with a constant borrowed from an unexpected place: binary search trees. An iTree has the same structure as a BST, and isolating a point behaves like an unsuccessful search in one. The paper takes the average length of that search from Bruno Preiss’s data structures textbook:
c(n) = 2H(n−1) − 2(n−1)/n, where H(i) is the harmonic number, approximated by ln(i) + 0.5772156649 (Euler’s constant).
s(x, n) = 2−E[h(x)] / c(n), where E[h(x)] is the average path length of x across all trees.
Put in the default n = 256. ln(255) = 5.5413, plus 0.5772 gives H(255) ≈ 6.1185 (the exact sum is 6.1204). So c(256) = 2 × 6.1185 − 2 × 255/256 = 12.2370 − 1.9922 = 10.24. A point isolated after 10.24 splits on average is exactly average, and scores 2−1 = 0.5.
| Average path length E[h(x)] | Score s (n = 256) | Reading |
|---|---|---|
| 2 | 0.873 | isolated almost immediately |
| 4 | 0.763 | strong anomaly |
| 8 | 0.582 | mildly unusual |
| 10.24 (= c(256)) | 0.500 | exactly average |
| 12 | 0.444 | normal |
| 14 | 0.388 | deep in the crowd |
The paper’s rules of thumb: scores very close to 1 are “definitely anomalies”, scores much smaller than 0.5 are “quite safe to be regarded as normal”, and if everything returns about 0.5, “the entire sample does not really have any distinct anomaly”. If you implement it yourself, note that the ln + 0.5772 shortcut drifts for small n. For n = 10 it gives 3.749 against an exact 3.858, and small n is exactly what you meet in leaves, where c(leaf size) is added to the depth.
Subsampling and number of trees: why 256 and 100?
Both defaults come straight from the 2008 paper. On subsample size ψ: “setting ψ to 28 or 256 generally provides enough details to perform anomaly detection across a wide range of data”. On trees: “path lengths usually converge well before t = 100”. scikit-learn keeps both: n_estimators=100 and max_samples="auto", meaning min(256, n_samples).
Small samples also improve detection, because of two failure modes the paper names. Swamping is “wrongly identifying normal instances as anomalies” when they sit too close to anomalies. Masking is “the existence of too many anomalies concealing their own presence”, such as a dense cluster of fraud from one ring. A subsample thins out both crowds: on the paper’s Mulcross data, AUC rose from 0.67 on the full sample to 0.91 with a subsample of 128.
| Subsample ψ (max_samples) | 16 | 64 | 256 | 1,024 | 4,096 |
|---|---|---|---|---|---|
| PR-AUC, mean of 3 runs | 0.61 | 0.75 | 0.76 | 0.75 | 0.74 |
On our data, 4,096 rows per tree did slightly worse than 256. One synthetic dataset proves nothing about yours, so tune ψ on a labelled validation month.
Isolation Forest complexity
The paper gives O(tψ log ψ) for training and O(nt log ψ) for scoring n points, so training cost does not grow with your dataset; a tree with ψ = 256 has at most 511 nodes. Scoring 283,748 instances of the KDD Cup 99 Http subset took 7.6 seconds in total on the authors’ 2008 setup.
What the contamination parameter actually does
This is where our 2,474 alerts came from. In scikit-learn, contamination changes no tree and no score. It only moves the line predict uses, via decision_function = score_samples - offset_; negative values are flagged.
contamination="auto", the default since version 0.22 (it was 0.1 before), setsoffset_ = -0.5. Becausescore_samplesreturns the opposite of the paper’s score, that means: flag every row with s > 0.5. The source code comment reads: “0.5 plays a special role as described in the original paper.”- A float in (0, 0.5] sets
offset_to that percentile of the training scores, giving “the expected number of outliers” in training.
But 0.5 is the “exactly average” point from the formula, not a fraud threshold. On our data 12.4% of rows scored above it, so the default asked analysts to review one transaction in eight.
PR-AUC and ROC-AUC do not change with contamination, because they use scores. And no contamination is “correct”. The true rate (0.75%) gave 70.7% precision and 70.7% recall; 0.5% gave 100% precision and missed a third of the fraud. The cleaner habit is to ignore predict, rank by score and cut at the number of cases your team can work, the “precision top-k” approach from the ULB fraud detection handbook.
Isolation Forest anomaly detection example on transaction data
Our test set is synthetic: 19,850 ordinary transactions and 150 planted anomalies (0.75%), with five features: log amount, hour, log distance from the usual location, card transactions in the last 24 hours, and log device age. The anomalies come in three kinds of 50. Card testing: $1–3 charges, 15–40 transactions a day, a brand-new device. Account takeover: large amounts at night, 500–5,000 km away, new device. Subtle: somewhat larger and farther, otherwise ordinary. We ran 100 trees with ψ = 256 in our own numpy implementation of the paper’s algorithm. scikit-learn 1.9.1 on the same data gave PR-AUC between 0.75 and 0.77 across five seeds, against 0.75 for ours.
| Group | Rows | Mean E[h(x)] | Mean score s | Share in top 150 alerts |
|---|---|---|---|---|
| Normal | 19,850 | 12.07 | 0.444 | 0.2% (44 rows) |
| Card testing | 50 | 4.96 | 0.715 | 100% |
| Account takeover | 50 | 4.74 | 0.726 | 100% |
| Subtle | 50 | 9.35 | 0.534 | 12% |
The last row changes how to read the 106 hits from the introduction. They were not a random 71% of the fraud: they were all of the loud fraud and almost none of the quiet kind. Isolation Forest finds what is rare, and fraud is only sometimes rare. A fraudster who copies a customer’s usual amount, time and place gets a path length close to everyone else’s, and no threshold will separate them. That is a job for supervised models trained on confirmed cases. Overall the ranking was strong (ROC-AUC 0.97, PR-AUC 0.75); random ranking would get a PR-AUC of 0.0075.
Isolation Forest in Python with scikit-learn
This snippet ran as written against scikit-learn 1.9.1 on a split of our synthetic set. X_train and X_test are numeric arrays; y_test holds known labels, used only for evaluation.
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.metrics import average_precision_score
iso = IsolationForest(n_estimators=100, max_samples=256,
contamination="auto", random_state=42)
iso.fit(X_train) # no labels needed
s = -iso.score_samples(X_test) # the paper's s(x, n): higher = stranger
print("PR-AUC:", round(average_precision_score(y_test, s), 3))
k = 50 # alerts your analysts can review
top = np.argsort(-s)[:k]
print("precision@k:", y_test[top].mean())
flags = iso.predict(X_test) # -1 = outlier, +1 = inlier
On a 5,000-row slice with 33 anomalies it printed PR-AUC 0.752 and precision@50 of 0.52, while predict flagged 609 rows. Watch the sign: score_samples is the negative of the paper’s score, so lower means more abnormal. In 1.9.1, fit also accepted a missing value without complaint. To add trees later, set warm_start=True, raise n_estimators and call fit again. For explanations, SHAP’s TreeExplainer has a dedicated code path for IsolationForest, so a reviewer can see which features shortened a flagged transaction’s path.
Isolation Forest evaluation metrics: why accuracy lies
A model that flags nothing scores 99.25% accuracy on our data. On the public credit card dataset from Andrea Dal Pozzolo and colleagues at ULB, with 492 frauds among 284,807 European card transactions (0.172%), it would score 99.83%. That dataset’s description says so directly: “Confusion matrix accuracy is not meaningful for unbalanced classification.” Use these instead:
- Precision: share of flagged rows that are fraud, your analysts’ hit rate. Recall: share of fraud you caught, your loss exposure.
- PR-AUC (average precision): the trade-off across all thresholds. Its baseline is the positive rate, so 0.75 at 0.75% prevalence is a hundredfold lift. Takaya Saito and Marc Rehmsmeier showed in PLOS ONE (2015) that it is more informative than ROC on imbalanced data.
- Precision@k: precision among the k top-scored rows, with k set to your daily review capacity.
With no labels, you can only check whether almost everything sits near 0.5. Once investigators close their first cases, those outcomes become your labels. Our overview of AI in risk management covers how that feedback loop is usually governed.
Isolation Forest with categorical features
scikit-learn converts the input to float32, so merchant type or country must be encoded first. The authors flagged the issue themselves under “Future Work” in the 2012 journal version: categorical data “have no ordering information”, and in mixed data they “will have a lesser impact as compared to continuous-valued attributes”. Each workaround costs something. One-hot encoding adds near-empty columns that random feature choice keeps picking. Ordinal encoding invents an order. Frequency encoding turns rare categories into small numbers, which suits isolation, but makes two different rare categories identical.
Limitations: masking, swamping, high dimensions and axis-parallel cuts
The 2012 paper admits iForest “fails to detect local clustered anomalies” and points to a slower variant, SCiForest. The bigger risk in fraud work is a wide table where few features carry signal: each split picks one feature at random, so every useless column takes a share of the cuts.
The 2012 paper says iForest “works well in high dimensional problems containing a large number of irrelevant attributes”. In that experiment, though, the authors used a Kurtosis test to choose an attribute subspace before building each tree. Without some feature selection, expect our result. Note that scikit-learn’s max_features subsamples features at random per tree, which is not the same as choosing the informative ones.
Extended Isolation Forest (Hariri et al.)
Standard iForest cuts only parallel to the feature axes. Sahand Hariri, Matias Carrasco Kind and Robert Brunner at the University of Illinois at Urbana-Champaign showed this leaves artifacts in score maps; an anomaly between two dense clusters “will get a very low score and be categorized as a nominal point”. Their Extended Isolation Forest (IEEE TKDE, 2021) splits with hyperplanes at random slopes, with “no appreciable difference” in computation time. It is not in scikit-learn 1.9.1; the authors publish a reference implementation on GitHub.
Isolation Forest vs random forest and other alternatives
The names are similar, but the jobs differ. Leo Breiman’s random forest is supervised: it needs labels, and each split is chosen to separate the classes. Isolation Forest needs no labels, splits at random and outputs a depth, not a class. In the 2008 benchmark it had the best AUC on 10 of 12 datasets against ORCA, LOF and random forests (ORCA won on Pima and Ionosphere), ran much faster, and LOF could not finish the largest datasets in reasonable time.
| Method | Needs labels? | Core idea | When to prefer it |
|---|---|---|---|
| Isolation Forest | No | Few random splits isolate anomalies | Large tabular data, fast first pass, no labels yet |
| Extended Isolation Forest | No | Random-slope hyperplane splits | Score artifacts matter, anomalies between clusters |
| Local Outlier Factor (Breunig et al., 2000) | No | Local density compared with neighbours | Smaller data with clusters of different density |
| One-class SVM (Schölkopf et al., 2001) | No (fits normal data) | Estimates the support of the normal distribution | Clean normal-only training data, modest size |
| Random forest / gradient boosting | Yes | Splits optimised to separate labelled classes | Once you have confirmed fraud labels |
Production stacks usually combine both: an unsupervised score for unlabelled patterns, feeding a supervised model. If you are buying rather than building, our comparison of AI fraud detection tools in 2026 covers the commercial side; for supervised versus unsupervised basics, start with what machine learning is.
FAQ
Is Isolation Forest supervised or unsupervised?
Unsupervised. It builds random trees on unlabelled data and scores each point by how quickly it gets isolated. Labels are useful only for evaluating the result and choosing a threshold.
How many trees does Isolation Forest need?
The 2008 paper found that path lengths “usually converge well before t = 100”, and 100 is the scikit-learn default. In our test, PR-AUC was flat from about 50 trees; a single tree was highly unstable.
What does contamination=”auto” mean in scikit-learn?
It sets offset_ to −0.5, so predict flags every point whose paper-style score s is above 0.5. It does not change the scores. On our data with 0.75% planted anomalies it flagged 12.4% of rows.
What is a good anomaly score in Isolation Forest?
Scores close to 1 are strong anomalies and scores well below 0.5 are normal. With the default subsample of 256, an average path length of 4 gives s = 0.76 and 12 gives s = 0.44. In practice, rank by score and cut at your review capacity.
Can Isolation Forest handle categorical variables?
Not natively. scikit-learn needs numeric input, so categories must be one-hot, ordinal or frequency encoded, each with a cost. The original authors listed categorical data as future work.
Isolation Forest vs LOF: which is better?
Isolation Forest scales linearly and needs no distance calculations. LOF compares local densities and copes with clusters of different density, but it is far slower on large data; in the 2008 benchmark it could not complete the largest datasets in reasonable time.
Can I use SHAP with Isolation Forest?
Yes. SHAP’s TreeExplainer includes a dedicated code path for scikit-learn’s IsolationForest, attributing the anomaly score to individual features so analysts can see why a case was flagged.
Before you deploy, score last month’s confirmed fraud and see where it lands in the ranking. If the cases you fear most sit around 0.5, no threshold will rescue them.
Sources
- Liu, F. T., Ting, K. M. and Zhou, Z.-H. (2008). Isolation Forest. Eighth IEEE International Conference on Data Mining (ICDM), pp. 413–422.
- Isolation Forest (ICDM 2008), author copy, LAMDA group, Nanjing University (PDF).
- Liu, F. T., Ting, K. M. and Zhou, Z.-H. (2012). Isolation-Based Anomaly Detection. ACM Transactions on Knowledge Discovery from Data 6(1), 1–39.
- Isolation-Based Anomaly Detection (TKDD), author copy, Nanjing University (PDF).
- Hariri, S., Carrasco Kind, M. and Brunner, R. J. (2021). Extended Isolation Forest. IEEE Transactions on Knowledge and Data Engineering 33(4), 1479–1489.
- Hariri, Carrasco Kind and Brunner. Extended Isolation Forest, arXiv:1811.02141 (v3, 2020).
- sahandha/eif: reference implementation of Extended Isolation Forest (GitHub).
- scikit-learn 1.9.1 documentation: sklearn.ensemble.IsolationForest.
- scikit-learn 1.9.1 user guide: Novelty and Outlier Detection.
- scikit-learn source code, sklearn/ensemble/_iforest.py (1.9.X branch).
- SHAP source code, shap/explainers/_tree.py (TreeExplainer, IsolationForest support).
- Saito, T. and Rehmsmeier, M. (2015). The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets. PLOS ONE 10(3), e0118432.
- Dal Pozzolo, A., Caelen, O., Johnson, R. A. and Bontempi, G. (2015). Calibrating Probability with Undersampling for Unbalanced Classification. IEEE SSCI, pp. 159–166.
- OpenML dataset 1597: creditcard, Dal Pozzolo, Caelen and Bontempi (ULB Machine Learning Group); European cardholders, September 2013; mirror of the Kaggle “Credit Card Fraud Detection” dataset.
- Reproducible Machine Learning for Credit Card Fraud Detection, practical handbook (ULB): Precision top-k metrics.
- Breunig, M. M., Kriegel, H.-P., Ng, R. T. and Sander, J. (2000). LOF: Identifying Density-Based Local Outliers. ACM SIGMOD, pp. 93–104.
- Schölkopf, B., Platt, J. C., Shawe-Taylor, J., Smola, A. J. and Williamson, R. C. (2001). Estimating the Support of a High-Dimensional Distribution. Neural Computation 13(7), 1443–1471.
- Breiman, L. (2001). Random Forests. Machine Learning 45, 5–32.
Papers, documentation and source code checked on 3 December 2026; DOIs resolved at api.crossref.org. Experiments are DTF calculations on synthetic data (calc.py and calc.json, fixed seed), cross-checked against scikit-learn 1.9.1.
