Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 98/ 160
05. Classical Machine Learning

Anomaly & Outlier Detection (Isolation Forest)

Detect rare events with isolation forests and score anomalies for monitoring workflows.

AdvancedIsolation Forest · Anomaly Score3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Anomalies are easy to separate from the crowd with a few random cuts, so points that get isolated quickly are flagged as unusual.

Think of it like…

Playing hide-and-seek in a crowd: someone standing alone at the edge is found after a couple of cuts of the room, while someone in the middle of a dense crowd needs many cuts before they're alone.

Where you’ve seen it

With n = 256 points per tree (the default max_samples), c(256) = 2(ln 255 + 0.5772) − 2 × 255 / 256 = 2 × 6.1185 − 1.9922 = 10.245. A transaction isolated after an average of 3 splits scores 2^(−3 / 10.245) = 2^(−0.293) = 0.816 (anomalous). A typical transaction with an average path length of 10.245 scores 2^(−1) = 0.5, and one buried deep in the data with path 12 scores 2^(−1.17) = 0.444. A payments team scores 1 million events a day with 100 trees and contamination=0.001, flagging the top 0.1% (1,000 events), but analysts can review only 100, so they work the top 100 by score and measure precision@100 on confirmed cases (31% in a labelled month: 31 of 100 reviewed alerts were true fraud or error, compared with 0.4% base rate). A SHAP-style per-feature contribution explains each alert ("amount 40× the customer's median; new country"), and scores are re-baselined weekly because behaviour drifts.

Words you’ll hear

Path length
Number of splits needed to isolate a point in a tree; short means anomalous.
Anomaly score
2^(−E[h]/c(n)); close to 1 for anomalies, about 0.5 for normal points.
Contamination
The assumed share of anomalies, used to set the decision threshold.
Subsample size (max_samples)
Points per tree; 256 is the typical default.

Visual diagram

Loading interactive diagram

Theory & deep dive

The algorithm and the score

Each isolation tree is built on a random subsample of ψ points (256 by default): pick a random feature, pick a random split value uniformly between that feature's minimum and maximum in the node, partition the points and recurse until each point is isolated or a maximum depth (⌈log₂ ψ⌉) is reached. The path length h(x) is the number of edges from the root to x's leaf (with a small adjustment c(size) for unfinished leaves). A forest of 100 trees averages h(x). Because the trees are random, there is no distance computation, no density estimation and no need for scaling, which gives low, near-linear training cost (O(t ψ log ψ)) and cheap scoring, and works with many features.

The score normalises path length by c(ψ) = 2H(ψ − 1) − 2(ψ − 1)/ψ, with H(i) ≈ ln i + 0.5772 (Euler's constant). For ψ = 256, c = 2 × (5.5413 + 0.5772) − 1.9922 = 10.245. Then s = 2^(−E[h]/c): an average path of 3 gives 0.816, a path equal to c gives 0.5, and path 12 gives 0.444. Scores close to 1 flag anomalies; if most points score about 0.5 the data has no clear anomalies. Using a small subsample is a feature, not a limitation: it reduces swamping (normal points near anomalies being mislabelled) and masking (many anomalies hiding each other), making the method more accurate and faster than using all rows.

Scores from path lengths

c(256) = 10.245. E[h] = 3 → 2^(−0.2928) = 0.816. E[h] = 10.245 → 2^(−1) = 0.5. E[h] = 12 → 2^(−1.171) = 0.444. Shorter paths mean higher scores.

Key takeaway: Anomalies are isolated in few random splits; the score normalises average path length so 0.5 is normal and values near 1 are anomalous.

Using it in practice: thresholds, evaluation and limits

Key parameters: n_estimators (100 to 300; scores stabilise quickly), max_samples (256 or auto; larger subsamples rarely help), max_features (1.0 by default) and contamination (a guess at the anomaly share; "auto" uses a fixed score threshold). Because the contamination is rarely known, prefer to rank by score_samples and choose the cut by review capacity or cost: with 1,000,000 events a day and 100 reviews, work the top 100. Evaluate with whatever labels exist: precision@k, recall of known incidents, ROC-AUC or PR-AUC on a labelled sample, or a synthetic test that injects realistic anomalies; compare with baselines such as robust z-scores, Local Outlier Factor, One-Class SVM or an autoencoder. Check stability across seeds and across time windows.

Limitations: axis-parallel random splits make it weak at anomalies defined by feature *relationships* (a plausible age and income that are jointly implausible; extended Isolation Forest uses random hyperplanes to help); local anomalies next to dense normal clusters are harder than global outliers; irrelevant features dilute the signal (select or engineer features that matter: ratios, customer-relative z-scores, velocity features); categoricals need encoding; and drift changes what is normal, so retrain on a rolling window and monitor score distributions. Build the workflow around the model: explainability (which features drove the score), thresholds by segment (a high-value merchant differs from a new one), feedback of confirmed cases into a supervised model once enough labels exist and periodic audits of what the model misses.

Alert budgeting

1,000,000 events/day, base rate 0.4% = 4,000 true issues. Reviewing the top 100 scores with precision 31% confirms 31 issues a day (0.8% recall of the 4,000). Raising review capacity to 500 at precision 22% finds 110; the team weighs that against analyst cost and builds a supervised model to raise precision.

Key takeaway: Rank by score and set the threshold from review capacity; engineer relative features, evaluate with precision@k and retrain as normal behaviour drifts.

How it works, step by step

Step 1 of 4
Analyst

1. Engineer meaningful features

Create customer-relative and velocity features and remove irrelevant columns; encode categoricals.

amount ÷ customer median · txns/hour
Key numbers at this step
Scaling
not required

When to use it & trade-offs

What it is

Isolation Forest detects anomalies by exploiting the fact that rare, different points are easy to isolate. It builds many random trees: each split picks a random feature and a random threshold between that feature's min and max in the current node, recursing until every point is alone. Anomalies sit in sparse regions, so they are separated after few splits (short average path length), while normal points need many. The anomaly score is s(x, n) = 2^(−E[h(x)] / c(n)), where E[h(x)] is the average path length over the trees and c(n) is the average path length of an unsuccessful search in a binary tree of n points; scores near 1 are anomalous, near 0.5 are normal. It needs no labels, scales linearly, handles high-dimensional numeric data and gives a ranking to feed monitoring and review workflows.

Why it matters: Fraud, intrusion, equipment faults and data-quality problems are rare and constantly changing, and labelled examples are scarce or outdated. Isolation Forest is a robust, fast unsupervised baseline that doesn't rely on distance or density estimation (which break down in high dimensions), and its score supports alert budgeting: review the top 100 events a day instead of drowning in thousands. Knowing its assumptions (anomalies are few and different, axis-parallel splits) and how to evaluate it without many labels is what makes it useful in practice.

When to reach for it

  • Fraud and abuse screening with few labels
  • Data-quality monitoring and sensor fault detection
  • Prioritising items for human review

When to avoid or be careful

  • Treating the contamination parameter as known truth
  • Throwing in dozens of irrelevant raw columns
  • Never retraining as behaviour drifts

Anomaly detection approaches

Isolation Forest
Best for: Fast unsupervised scoring on many numeric features

Strengths: Linear time; no scaling or distances; good baseline.

Watch out: Axis-parallel splits miss relationship-based anomalies.

Local Outlier Factor
Best for: Local density-based anomalies in moderate dimensions

Strengths: Finds anomalies near dense clusters.

Watch out: Distance-based; slow and weak in high dimensions.

Autoencoders or supervised models
Best for: Complex patterns or when labels exist

Strengths: Capture relationships; supervised gives higher precision.

Watch out: Need more data, tuning or labels.

Interview signals & numbers to know

When this topic comes up

  • “Find unusual transactions without labels”
  • “We can only review 100 alerts a day”
  • Anomaly score from path length
  • Contamination
  • Precision@k

Benchmarks & rules of thumb

c(256) = 10.245 -
normalising path length for 256 samples
0.816 / 0.5 / 0.444 -
scores for path 3, 10.245 and 12
256 -
default points per tree

Common mistakes & follow-ups

Common interview mistakes

  • Using the default contamination to decide how many alerts to send.
  • Evaluating only with accuracy on a 0.4% base rate.
  • Using raw amounts instead of customer-relative features.

Likely interviewer follow-ups

  • Why are anomalies isolated faster in an isolation forest?
  • How would you choose the alert threshold?
  • What are the limitations of Isolation Forest?
Interview tip: Mention alert budgeting and precision@k. It shows you design anomaly detection around analyst capacity, not just a score.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Anomaly & Outlier Detection (Isolation Forest) with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
t-SNE & UMAP for Visualization
Next topic
Recommendation Systems (Collaborative & Content-Based)