Download Anomaly detection interview prep and more Study notes Machine Learning in PDF only on Docsity!
PROBLEM 2
Anomaly Detection
Automatically identifying data points that are surprisingly different from normal ML Interview Preparation Guide
What Is Anomaly Detection? Anomaly detection means automatically finding data points that are surprisingly different from what is normal. Like a doctor looking at a heart rate monitor — 72, 74, 71, 73, 72, 74, 180... something is wrong! Real World Examples: Fraud detection (credit card used in 3 countries in 1 hour), server monitoring (CPU spikes to 99% at 3am), manufacturing (machine vibrating differently before it breaks), finance (stock drops 40% in 5 minutes), e-commerce (user adds 500 items to cart — bot behavior). Step 0: Clarify the Problem First
- What kind of data? Time series (CPU over time)? Tabular (one row per transaction)? Or a single snapshot?
- Labeled or unlabeled? Do we have examples of past anomalies? Most real-world anomaly problems are unlabeled.
- How fast do we need to detect it? Real-time (fraud while card is swiped)? Or batch (daily report)?
- Cost of false alarm vs. missed anomaly? Missing fraud = lose money. False alarm on fraud = block a legitimate customer.
- How rare are anomalies? Usually < 1% of data — this is a class imbalance problem. Step 1: Types of Anomalies Not all anomalies are the same. There are 3 distinct types you must know: Type 1: Point Anomaly A single data point is weird. Example: CPU = 45%, 47%, 46%, 45%, 98%, 46%, 45% — one bad point stands out. Type 2: Contextual Anomaly A value that is normal in one context but weird in another. CPU at 90% at 2pm on a weekday = NORMAL (peak traffic). CPU at 90% at 3am on Sunday = ANOMALY. Same value, completely different meaning depending on context. This is why time-of-day features matter so much.
For Tabular Data (Transactions, User Behavior)
- amount_vs_user_avg — how unusual is this amount for THIS user?
- time_since_last_transaction — 3 transactions in 10 seconds = suspicious
- transactions_last_hour — velocity check
- is_new_country — user never bought from here before
- is_new_device — new device ID Step 4: Statistics and Math Z-Score z = (x - μ) / σ — Flag as anomaly if |z| > 3. Simple and fast. Works well for normally distributed data. Problem: real data is often skewed. Modified Z-Score (More Robust) Instead of mean and std, use median and MAD (Median Absolute Deviation). The median is resistant to outliers — one extreme value does not drag it.
- MAD = median(|x ᵢ - median(x)|)
- Modified Z = 0.6745 × (x - median) / MAD IQR Method (Interquartile Range)
- Q1 = 25th percentile, Q3 = 75th percentile
- IQR = Q3 - Q
- Lower bound = Q1 - 1.5 × IQR
- Upper bound = Q3 + 1.5 × IQR Anything outside these bounds is an outlier. No assumption about distribution shape. This is what box plots show. Mahalanobis Distance (For Multiple Features) What if you have 2 metrics — CPU and memory? A point might look normal on each individually but anomalous in combination. CPU = 70% and Memory = 95% together is unusual even if each alone might be seen sometimes. Mahalanobis Distance measures how far a point is from the center of the distribution, accounting for the correlation between features:
- D² = (x - μ) ᵀ Σ ⁻¹ (x - μ)
- x = your data point (vector of all features)
- μ = mean vector
- Σ ¹ = inverse of the covariance matrix (captures how features relate to each other)⁻ This is a generalization of z-score to multiple dimensions. It accounts for correlations between features when measuring distance. Step 5: Models — From Simple to Complex Category 1: Statistical Methods
3-Sigma Rule
Flag if: |x - mean| > 3 × std. Instant, no training needed. Assumes normal distribution, sensitive to outliers in the baseline period.
CUSUM (Cumulative Sum)
Designed to detect when a metric shifts to a new level — not just spikes. S_t = max(0, S_{t-1} + (x_t - μ - k)). When S_t exceeds a threshold → alert. Analogy: you are weighing yourself daily. CUSUM detects when your weight has been consistently trending upward for a week, not just one heavy meal.
- Pros: Great for detecting sustained shifts, widely used in manufacturing quality control Category 2: Unsupervised ML (No Labels Needed) These are the most commonly used because you almost never have labeled anomaly data in practice.
Isolation Forest
Intuition: anomalies are easy to isolate. Normal points are surrounded by neighbors — you need many random splits to isolate them. Anomalies are alone — you isolate them in very few splits. The anomaly score is 1 / (average path length). Higher score = more anomalous.
- Pros: Works well on high-dimensional data, fast, no assumptions about distribution
- Cons: Does not capture time patterns (each point treated independently)
Local Outlier Factor (LOF)
A point is anomalous if its neighborhood is much denser than it is. LOF score ≈ 1 means normal density; LOF >> 1 means the point is in a sparser region than its neighbors. Analogy: people clustered at a party — the anomaly is someone standing alone far from all groups.
- Pros: Detects local anomalies even when different clusters have different densities
Category 4: Time-Series Specific Models
STL + Residual Analysis
Decompose the series: y(t) = Trend + Seasonality + Residual. After removing normal patterns (weekly cycle, growth trend), the residuals should be random noise. A large residual = something unusual happened. Flag residuals beyond 3σ.
ARIMA-Based Anomaly Detection
Fit ARIMA on historical normal data. At each new time point, ARIMA predicts the expected value and a confidence interval. If actual value falls outside the interval → anomaly. ARIMA predicts: 45% CPU ± 10%. Actual: 92% → outside [35%, 55%] → ANOMALY.
Facebook Prophet for Anomaly Detection
Fit Prophet model, generate prediction intervals (e.g., 99% confidence), and flag points outside them. Very practical for business metric monitoring with daily/weekly patterns. Model Selection Guide Scenario Recommended Model Have labeled anomalies XGBoost/LightGBM with class weights + SMOTE Time series, need baseline STL residuals + 3-sigma rule Time series, need intervals ARIMA/Prophet confidence intervals Time series, best accuracy LSTM Autoencoder Tabular, no labels Isolation Forest Multi-feature relationships matter Autoencoder (captures correlations) Small dataset, no labels One-Class SVM Step 6: Evaluation The Label Problem
- If you have labels: Use Precision, Recall, F1, AUC-PR (NOT accuracy). Use time- based train/test split.
- Inject synthetic anomalies: Take normal data, artificially inject anomalies, evaluate how many you catch.
- Human evaluation: Deploy model, send alerts to humans, track what % were actually real anomalies.
The Threshold Problem Most anomaly models give a score, not a binary yes/no. You choose a threshold. Lower threshold = more alerts = higher recall, lower precision. Higher threshold = fewer alerts = lower recall, higher precision. Practical advice: Start conservative (high threshold → fewer alerts). Nothing kills trust in a system faster than too many false alarms. Engineers start ignoring alerts → you miss real ones. Step 7: Production Real-Time vs. Batch Detection
- Real-time (online): Score each point as it arrives. Use for fraud detection, server monitoring. Model must be very fast (milliseconds). Use stateless models: Z-score, Isolation Forest.
- Batch: Score a window of data periodically. Use for daily business metric reviews, log analysis. Can use heavier models: LSTM Autoencoder. Handling Seasonality in Production Your server always has high CPU from 9am–5pm. Your model should not alert on that. Fix: train separate models for different contexts (business hours vs. off-hours, weekday vs. weekend). Or condition on time as a feature so the model learns that 80% CPU is normal at 2pm. Concept Drift The definition of normal changes over time: your app grows, baseline CPU increases; you deploy a new service, memory usage pattern changes; holiday season brings different traffic patterns. Fix: Use a rolling training window — only train on the last 30 days of data, not all history. Alert Fatigue — The Real Enemy The #1 failure mode in production anomaly detection is NOT a bad model — it is too many alerts. If engineers get 50 alerts per day and most are false alarms, they start ignoring all alerts, and a real critical issue gets missed.
- Alert grouping: Multiple anomalies from the same root cause → one alert
- Severity levels: P1 (wake me up now) vs P3 (email in morning)