HomeArtificial IntelligenceIsolation Forest explained: score, contamination, Python

Isolation Forest explained: score, contamination, Python

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.

anomaly scorecontaminationscikit-learnfraud detection

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:

  1. Take a random subsample of the data (256 rows by default).
  2. Pick a feature at random, then a split value uniformly at random between that feature’s minimum and maximum in the current node.
  3. 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
20.873isolated almost immediately
40.763strong anomaly
80.582mildly unusual
10.24 (= c(256))0.500exactly average
120.444normal
140.388deep 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.

Detection quality vs number of treesPR-AUC on 20,000 synthetic transactions with 0.75% anomalies, subsample 256, three random forests per setting. 1 trees: PR-AUC mean 0.1597 (range 0.1209–0.1868); 5 trees: PR-AUC mean 0.5506 (range 0.458–0.6428); 10 trees: PR-AUC mean 0.6055 (range 0.4933–0.6787); 25 trees: PR-AUC mean 0.7243 (range 0.7106–0.7328); 50 trees: PR-AUC mean 0.7571 (range 0.7356–0.7851); 100 trees: PR-AUC mean 0.7537 (range 0.7462–0.7667); 200 trees: PR-AUC mean 0.7568 (range 0.7462–0.7636). Random ranking would score 0.0075.Detection quality vs number of treesDecodeTheFuture.orgisolation-forest-explainedChartimage/svg+xml© DecodeTheFuture.orgPR-AUC (mean of 3 runs; band = min to max)0.00.20.40.60.8151025501002000.75 at the default 100one tree: 0.16number of trees (n_estimators, log scale)
PR-AUC against the number of trees, subsample 256, three independently seeded forests per setting. One tree is a lottery; by 50 trees the curve is flat. Source: DTF calculation (calc.py, seed 42).
Subsample ψ (max_samples)16642561,0244,096
PR-AUC, mean of 3 runs0.610.750.760.750.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), sets offset_ = -0.5. Because score_samples returns 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.

Same model, different contamination: precision and recallOne fitted Isolation Forest (100 trees, subsample 256) on 20,000 rows with 150 planted anomalies. Only the threshold changes. contamination auto: flags 2474, precision 0.0546, recall 0.9; contamination 0.001: flags 20, precision 1.0, recall 0.1333; contamination 0.0025: flags 50, precision 1.0, recall 0.3333; contamination 0.005: flags 100, precision 1.0, recall 0.6667; contamination 0.0075: flags 150, precision 0.7067, recall 0.7067; contamination 0.01: flags 200, precision 0.535, recall 0.7133; contamination 0.02: flags 400, precision 0.2825, recall 0.7533; contamination 0.05: flags 1000, precision 0.123, recall 0.82; contamination 0.1: flags 2000, precision 0.0665, recall 0.8867.Same model, different contamination: precision and recallDecodeTheFuture.orgisolation-forest-explainedChartimage/svg+xml© DecodeTheFuture.orgprecisionrecallcontaminationalerts raised0%25%50%75%100%‘auto’2,4740.1%200.25%500.5%1000.75%1501%2002%4005%1,00010%2,000
One fitted forest, nine thresholds. The ranking never changes, only the number of alerts. The top 100 alerts were all real; recall then stalls near 71% until alert volume explodes. Source: DTF calculation.

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.

How many splits it takes to isolate a transactionShare of transactions by average path length E[h(x)] over 100 trees with subsample 256. Normal transactions: mean 12.065. Card testing: 4.959. Account takeover: 4.744. Subtle anomalies: 9.348. c(256) = 10.24, where the anomaly score equals 0.5.How many splits it takes to isolate a transactionDecodeTheFuture.orgisolation-forest-explainedChartimage/svg+xml© DecodeTheFuture.orgnormal (19,850)planted anomalies (150)share of each group, by average path length0%10%20%30%c(256) = 10.2score s = 0.5card testingand takeoversubtle3579111315average path length E[h(x)], splits (shorter = more anomalous)
Average path length per transaction. Card-testing and takeover cases are isolated after about 5 splits, normal rows after about 12. The subtle cases sit in between, mixed with the tail of normal traffic. Source: DTF calculation.
GroupRowsMean E[h(x)]Mean score sShare in top 150 alerts
Normal19,85012.070.4440.2% (44 rows)
Card testing504.960.715100%
Account takeover504.740.726100%
Subtle509.350.53412%

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.

Irrelevant features dilute Isolation ForestSame 5 transaction features plus 0, 5, 20 or 50 columns of pure noise; 100 trees, subsample 256, mean of 3 runs. 0 irrelevant features: PR-AUC 0.7607; 5 irrelevant features: PR-AUC 0.7091; 20 irrelevant features: PR-AUC 0.3834; 50 irrelevant features: PR-AUC 0.0964.Irrelevant features dilute Isolation ForestDecodeTheFuture.orgisolation-forest-explainedChartimage/svg+xml© DecodeTheFuture.orgPR-AUC, mean of 3 runs0.00.20.40.60.85 real features0.76+ 5 noise columns0.71+ 20 noise columns0.38+ 50 noise columns0.10
The same five transaction features plus columns of pure random noise. With 50 irrelevant columns PR-AUC falls from 0.76 to 0.10. Source: DTF calculation, 100 trees, ψ = 256, mean of 3 runs.

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.

MethodNeeds labels?Core ideaWhen to prefer it
Isolation ForestNoFew random splits isolate anomaliesLarge tabular data, fast first pass, no labels yet
Extended Isolation ForestNoRandom-slope hyperplane splitsScore artifacts matter, anomalies between clusters
Local Outlier Factor (Breunig et al., 2000)NoLocal density compared with neighboursSmaller data with clusters of different density
One-class SVM (Schölkopf et al., 2001)No (fits normal data)Estimates the support of the normal distributionClean normal-only training data, modest size
Random forest / gradient boostingYesSplits optimised to separate labelled classesOnce 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

  1. Liu, F. T., Ting, K. M. and Zhou, Z.-H. (2008). Isolation Forest. Eighth IEEE International Conference on Data Mining (ICDM), pp. 413–422.
  2. Isolation Forest (ICDM 2008), author copy, LAMDA group, Nanjing University (PDF).
  3. 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.
  4. Isolation-Based Anomaly Detection (TKDD), author copy, Nanjing University (PDF).
  5. Hariri, S., Carrasco Kind, M. and Brunner, R. J. (2021). Extended Isolation Forest. IEEE Transactions on Knowledge and Data Engineering 33(4), 1479–1489.
  6. Hariri, Carrasco Kind and Brunner. Extended Isolation Forest, arXiv:1811.02141 (v3, 2020).
  7. sahandha/eif: reference implementation of Extended Isolation Forest (GitHub).
  8. scikit-learn 1.9.1 documentation: sklearn.ensemble.IsolationForest.
  9. scikit-learn 1.9.1 user guide: Novelty and Outlier Detection.
  10. scikit-learn source code, sklearn/ensemble/_iforest.py (1.9.X branch).
  11. SHAP source code, shap/explainers/_tree.py (TreeExplainer, IsolationForest support).
  12. 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.
  13. Dal Pozzolo, A., Caelen, O., Johnson, R. A. and Bontempi, G. (2015). Calibrating Probability with Undersampling for Unbalanced Classification. IEEE SSCI, pp. 159–166.
  14. 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.
  15. Reproducible Machine Learning for Credit Card Fraud Detection, practical handbook (ULB): Precision top-k metrics.
  16. Breunig, M. M., Kriegel, H.-P., Ng, R. T. and Sander, J. (2000). LOF: Identifying Density-Based Local Outliers. ACM SIGMOD, pp. 93–104.
  17. 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.
  18. 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.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments