Anomaly Detection
Find rare, suspicious and faulty behaviour without confusing every unusual event with an error. Learn statistical, distance, density, isolation, boundary and reconstruction methods—and turn scores into reliable operational decisions.
alert if s(x) ≥ τBy the End of This Level, You Can
Six Ideas Behind Reliable Detection
An anomaly detector estimates how strongly an observation disagrees with learned normal behaviour.
Normal behaviour depends on population, time and business context.
Larger or smaller values indicate stronger abnormality, depending on the method.
A threshold converts ranked suspicion into alerts or decisions.
Some algorithms use it to estimate the score cut-off.
A point can be normal globally but strange inside its local context.
Reviewed alerts provide labels, costs and new failure modes.
Anomaly Is a Relationship, Not a Permanent Label
The same value can be expected in one context and dangerous in another.
A ₹2,00,000 card purchase among transactions normally below ₹5,000.
High electricity usage may be normal at noon but suspicious at 3 a.m.
Each network request looks valid, but their rapid pattern resembles an attack.
Anomaly detection begins by defining normal behaviour for a specific population and time window. Rare does not automatically mean wrong: a new high-value customer, a festival sales spike or an uncommon medical condition may be valid. Conversely, a harmful event can be individually ordinary but suspicious when its timing, order or surrounding events are considered. Write the detection unit, context variables, decision latency and investigation action before selecting an algorithm.
A temperature of 38°C is ordinary for industrial equipment but abnormal for a healthy human.
Interview answers should define what “normal” means before naming Isolation Forest.
An anomaly is not automatically fraud, failure or malicious behaviour.
Statistical Rules Measure Deviation from a Reference Distribution
Simple baselines are transparent, fast and often surprisingly effective.
z = (x − μ) / σMean and standard deviationUseful for roughly symmetric data without strong outlier contamination.
[Q₁−k·IQR, Q₃+k·IQR]Quartile fencesRobust to extreme values and easy to explain.
|x−median| / MADRobust central deviationThe median and median absolute deviation resist outlier influence.
d²=(x−μ)ᵀΣ⁻¹(x−μ)Correlation-aware distanceMeasures deviation using the covariance geometry of multiple features.
Mean and standard deviation are themselves affected by anomalies, so classical z-scores can hide extreme points by inflating the estimated spread. Median, IQR and MAD give robust alternatives. In multiple dimensions, treating every feature independently misses unusual combinations: height and weight may each look normal while their joint combination is rare. Mahalanobis distance handles correlation, but covariance estimation becomes unstable with too few observations, many features or heavy contamination.
For [10, 11, 10, 12, 60], the mean moves toward 60 while the median stays near the normal group.
Start with an interpretable robust baseline before defending a complex detector.
A universal “three sigma” rule is not valid for every distribution.
Anomaly Scores and Decision Thresholds Solve Different Problems
The model ranks unusual events; the operating policy decides which events receive action.
Distance, density, isolation depth, boundary position or reconstruction error produces s(x).
Use labelled validation data, historical alert rates or reviewed examples.
Choose τ using missed-event cost, false-alert cost and investigator capacity.
A detector can rank events well while still producing a poor alert system because its threshold is unsuitable. Lower thresholds normally increase recall and workload; higher thresholds reduce alerts but may miss costly events. Accuracy is misleading when anomalies are rare. Prefer precision, recall, F1, precision–recall curves, recall at a fixed alert budget, false positives per hour and cost-weighted utility. When labels are delayed, evaluate ranking quality on the reviewed subset while carefully accounting for selection bias.
If analysts can inspect 100 alerts daily, evaluate how many true incidents occur in the top 100 scores.
Separate model threshold from business action threshold in system-design answers.
Setting contamination to 1% does not prove exactly 1% of future events are abnormal.
🚨 Anomaly Score & Threshold Workbench
Calculate scores from real point geometry. Compare global, neighbour, density and isolation evidence; then observe how the threshold changes alerts and evaluation.
Isolation Forest Finds Points That Are Easy to Separate
Random recursive partitions isolate rare and extreme observations in fewer splits.
Build many small randomized trees.
Select a feature at random.
Draw a value between observed minimum and maximum.
Count splits required to isolate each observation.
Shorter expected paths produce larger anomaly scores.
Isolation Forest does not estimate a probability density and does not compare every pair of observations. It exploits the idea that anomalies are few and have unusual feature values, making them easier to isolate with random axis-aligned partitions. Each tree gives a path length; the forest normalizes the average length relative to a random binary-search-tree expectation. Subsampling improves speed and can strengthen isolation. Performance weakens when anomalies form dense groups, are visible only after rotations, or differ through context omitted from the features.
A point far from the main cloud may require two splits, while a central point survives many partitions.
Time is roughly linear in tree count, subsample size and tree depth—not quadratic in all rows.
An Isolation Forest score is not automatically a calibrated fraud probability.
🌲 Isolation Tree Path Laboratory
Follow actual recursive partitions and compare how quickly representative points become isolated.
Neighbour Methods Detect Local Abnormality
Distance and density methods compare an observation with nearby reference points.
Large values indicate that the observation lies far from available examples.
s(x)=distance to k-th NNCompares a point’s local reachability density with its neighbours’ densities.
LOF(x) ≈ neighbour density / own densityA kernel separates normal training observations from the origin in feature space.
decision_function(x) < 0Global distance can incorrectly flag every point in a sparse but valid group. LOF adjusts for local density by asking whether a point is substantially less dense than its neighbours. One-Class SVM learns a flexible boundary controlled by the kernel, gamma and ν; it is powerful but sensitive to scaling and tuning. All distance-based methods suffer in high dimensions unless features are meaningful, scaled and sufficiently supported by data. Novelty detection also differs from outlier detection: novelty models are fitted on clean normal data, while outlier methods expect contamination during fitting.
A point beside a sparse rural cluster may be globally remote but locally normal.
Explain why LOF handles varying local density better than one global distance cut-off.
LOF values from different datasets are not directly comparable risk probabilities.
Autoencoders Detect Patterns They Cannot Reconstruct
A neural network learns to compress and rebuild representative normal observations.
z = fθ(x)Maps the input to a smaller or constrained latent representation.
x̂ = gφ(z)Reconstructs the input from learned normal structure.
s(x)=‖x−x̂‖²Large reconstruction error may indicate unfamiliar behaviour.
An autoencoder trained mainly on normal patterns may reconstruct those patterns accurately and unfamiliar inputs poorly. This assumption is not guaranteed: an over-capacity network can learn the identity function and reconstruct anomalies too. Restrict capacity, regularize, validate on held-out normal and abnormal examples, and inspect error by feature rather than using total loss alone. For images or sequences, convolutional and recurrent variants can model structure, but their threshold still requires operational validation.
A model trained on smooth machine vibration may reconstruct routine cycles but miss an abrupt bearing fault pattern.
State training data, bottleneck, loss, score and threshold when explaining the pipeline.
High reconstruction error can also come from harmless distribution shift or bad preprocessing.
Time, Drift and Feedback Determine Production Quality
A detector that works offline can fail when normal behaviour changes.
Use hour, weekday, rolling baselines, rate of change and event order.
Track score distributions, alert rate, feature drift and confirmed incident rate.
Capture reason codes, confirmed cases and false-alert explanations.
Route uncertain events for review instead of applying irreversible automatic action.
Production anomalies arrive as a stream, not a frozen table. Normal behaviour changes with seasons, promotions, equipment age, user growth and policy. Use chronological validation where future information must not enter training, and never construct rolling features with future values. Monitor both the raw features and score distribution. Retraining on unreviewed recent data can absorb attacks or faults into the definition of normal, so use guarded update windows and confirmed feedback.
Festival-week purchase volume may trigger a detector trained only on ordinary weeks.
Strong system answers include alert queues, feedback labels, drift and safe fallback actions.
Automatically retraining on every recent event can teach the detector that failures are normal.
🎬 Anomaly Detection — Visual Flow
Move from an operational definition of abnormality to monitored action.
What unit, context and harm matter?
Protect training data and fit preprocessing.
Use statistical, local, isolation, boundary or reconstruction evidence.
Balance recall, precision, cost and capacity.
Capture outcomes and detect drift.
Trace k-NN Anomaly Scoring from First Principles
Follow every distance calculation, neighbour sort, score selection and threshold comparison. The cursor returns through both loops exactly as Python executes.
—Waiting for print(...)
Detection Logic Before Libraries
Use these compact procedure maps for revision, coding and interviews.
- Fit the median on reference observations.
- Calculate absolute deviations from the median.
- Fit the median absolute deviation.
- Score each observation with robust deviation.
- Select and validate an operational threshold.
- Draw a subsample for each tree.
- Randomly choose a feature and split value.
- Partition recursively until isolation or depth limit.
- Average normalized path lengths across trees.
- Rank shorter paths as more anomalous.
- Find the k nearest neighbours of each point.
- Calculate k-distance and reachability distances.
- Estimate each local reachability density.
- Compare neighbour density with the point’s density.
- Rank LOF values substantially above one.
- Fit preprocessing on trusted training data.
- Train encoder and decoder to reconstruct inputs.
- Calculate validation reconstruction errors.
- Choose a threshold using labels or alert budget.
- Monitor error distribution and failure examples.
💻 Anomaly Detection Challenges
Attempt each program independently. Workspaces, hints and model programs remain collapsed initially.
Test Your Detection Reasoning
Select one answer per question. Results show your choice, the correct answer and a clear explanation.
Choose Detection Like an ML Engineer
Start with the data-generating process, labels and operating cost.
Use a domain rule, IQR or robust MAD baseline and explain every alert.
Try Isolation Forest with leakage-safe preprocessing and validated contamination.
Compare LOF or neighbour scores after meaningful scaling and dimension control.
Consider novelty detection with One-Class SVM or an autoencoder.
Build rolling and seasonal features or use a sequence reconstruction model.
Optimize recall or precision at a fixed top-K alert budget and diversify the queue.
🎤 Anomaly Detection — Interview Questions
Answer aloud before selecting Show Answer for each explanation.
A Useful Detector Connects Rarity to Safe Action
Specify normality and context.
Calculate transparent evidence.
Prioritize limited attention.
Apply cost-aware thresholds.
Use feedback and drift monitoring.
Anomaly detection is not the search for strange numbers; it is the disciplined design of evidence, thresholds and responses for behaviour that matters.
Eight Practical Detection Habits
Define the event unit and operational context before choosing an algorithm.
Plot raw values and score distributions before trusting a threshold.
Use robust scaling when anomalies can distort mean and standard deviation.
Keep threshold selection separate from detector fitting.
Evaluate precision and recall at the actual review capacity.
Inspect false positives by segment, time and source.
Protect retraining data from unreviewed attacks and failures.
Provide reason codes and safe human-review paths for consequential alerts.
Strengthen Rare-Event Reasoning
Calculate intermediate values and defend the operational decision.
- 01
Calculate z-scores for six sensor readings and identify threshold sensitivity.
- 02
Find Q₁, Q₃, IQR and both outlier fences for a transaction sample.
- 03
Calculate the median absolute deviation and robust scores.
- 04
Find every pairwise distance in a five-point 2-D dataset.
- 05
Calculate each point’s second-neighbour anomaly score.
- 06
Explain why scaling changes neighbour-based detection.
- 07
Trace two isolation-tree paths and compare their depths.
- 08
Explain how subsampling helps Isolation Forest.
- 09
Compare global distance and LOF on unequal-density clusters.
- 10
Explain ν and gamma in a One-Class SVM.
- 11
Design an autoencoder anomaly score for multivariate sensors.
- 12
Choose a threshold for an investigation budget of 50 alerts daily.
- 13
Compare ROC-AUC and PR-AUC under 0.1% anomaly prevalence.
- 14
Design a chronological validation and drift-monitoring plan.
