Knowledge / Artificial Intelligence and Data Science / Anomaly detection

Anomaly detection

Artificial Intelligence and Data Science (B.E./B.Tech) · Machine learning · free study notes for exams, placements and interviews

In short

Anomaly detection finds the rare observations that do not follow the pattern of the rest of the data - a ₹2 lakh UPI transfer at 3 a.m. from a phone that normally spends ₹200, a bearing vibration spike, a sudden surge in server error logs. It matters because the interesting events in banking, manufacturing, telecom and cybersecurity are exactly the rare ones, and normal supervised learning drowns them: a classifier that calls everything "normal" is 99.9% accurate and useless. Indian university ML and data-science papers examine it under unsupervised learning, with statistical tests (z-score, IQR, Grubbs, Mahalanobis) and algorithms (isolation forest, LOF, one-class SVM, autoencoders); GATE DA asks distance and probability-based outlier questions. Analytics interviews at HDFC, ICICI, Paytm, PhonePe, Razorpay, Flipkart, TCS, Infosys and Wipro ask it as the standard "highly imbalanced data" question.

Explained

What counts as an anomaly, and the three learning settings

Statistical methods

Distance, density and tree-based algorithms

Step-by-step workflow

  1. Define the anomaly in business terms - fraud, failure, data-entry error - and who acts on the alert. Different definitions need different methods.
  2. Explore: boxplots, histograms, scatter and correlation; separate genuine outliers from data-quality faults (−999 sentinels, 0 for missing, unit mix-ups).
  3. Prepare features: scale (standardise or robust-scale) for every distance/density method - isolation forest and trees do not need it; engineer deviation features (amount ÷ customer's 30-day median, time since last txn, velocity counts).
  4. Choose the setting (supervised / novelty / unsupervised) by what labels you actually have.
  5. Fit on normal-ish data, set contamination from business capacity (how many alerts per day can analysts review?).
  6. Score and threshold: pick the cut-off from a precision-recall curve or from the top-N alerts the team can handle; keep the score, not just the label.
  7. Validate: on labelled holdout use PR-AUC, recall at fixed alert volume, precision@k; without labels use stability, expert review of the top alerts, and injected synthetic anomalies.
  8. Explain the alert: feature contribution (SHAP, per-feature z-score, reconstruction error per feature) - a bank analyst must know *why* it fired.
  9. Deploy and monitor: retrain on drift, track alert rate, false-positive feedback from investigators, and keep a human in the loop for action.

Imbalanced-data handling and evaluation

Indian regulatory and practice context

Key points

Formulas and examples

Z-score: z = (x − μ)/σ — x = observation, μ = mean, σ = standard deviation (same units as x); flag |z| > 3.
Modified z-score: M = 0.6745 (x − median)/MAD, where MAD = median(|xi − median|); flag |M| > 3.5. 0.6745 ≈ 0.75 quantile of the standard normal, making MAD comparable to σ.
IQR rule: IQR = Q3 − Q1; outlier if x < Q1 − 1.5·IQR or x > Q3 + 1.5·IQR (extreme: 3.0·IQR).
Grubbs' statistic: G = max|xi − x̄| / s, n = sample size, s = sample SD; reject the extreme point if G > Gcrit(n, α).
Mahalanobis distance: D²(x) = (x − μ)ᵀ Σ⁻¹ (x − μ); p = number of features; threshold at χ²(p, 1−α). Dimensionless.
Multivariate Gaussian score: p(x) = (2π)−p/2|Σ|−1/2 exp(−D²/2); flag p(x) < ε.
LOF: lrdk(A) = 1 / ( mean of reachability-distk(A, B) over B in Nk(A) ); LOFk(A) = mean over B of lrdk(B) / lrdk(A).
Isolation Forest: s(x, n) = 2−E[h(x)]/c(n), where E[h(x)] = average path length over trees and c(n) = 2H(n−1) − 2(n−1)/n ≈ 2(ln(n−1) + 0.5772) − 2(n−1)/n is the average path length of an unsuccessful BST search. s ∈ (0,1): s → 1 anomaly, s ≈ 0.5 normal.
Autoencoder / PCA score: E(x) = ‖x − x̂‖² (squared reconstruction error, units = squared feature units after scaling).
Imbalanced metrics: Precision = TP/(TP+FP); Recall = TP/(TP+FN); Fβ = (1+β²)·P·R/(β²·P + R); MCC = (TP·TN − FP·FN)/√((TP+FP)(TP+FN)(TN+FP)(TN+FN)).

Example 1 - z-score vs IQR vs modified z-score on UPI amounts (₹). Data (n = 12): 120, 150, 180, 200, 210, 220, 240, 260, 280, 300, 320, 9000.

Example 2 - Mahalanobis distance with correlated features. Features: monthly income (₹ '000) and loan EMI (₹ '000), μ = (50, 15), Σ = [[100, 40], [40, 25]].

Example 3 - Isolation Forest score. Dataset n = 256, a point has average path length E[h(x)] = 4.2 across 100 trees.

Example 4 - Threshold choice from costs (card fraud). 10,00,000 transactions/month, fraud rate 0.05% → 500 frauds. Average fraud loss ₹8,000; cost of investigating/blocking a genuine transaction ₹150.

ThresholdAlertsFrauds caught (recall)FPPrecisionFraud loss saved (₹)FP cost (₹)Net (₹)
High (strict)1,000300 (60%)70030.0%24,00,0001,05,00022,95,000
Medium5,000425 (85%)4,5758.5%34,00,0006,86,25027,13,750
Low (loose)20,000475 (95%)19,5252.4%38,00,00029,28,7508,71,250

Example 5 - metrics on an imbalanced confusion matrix. TP = 425, FP = 4,575, FN = 75, TN = 9,94,925.

Method comparison

MethodSettingHandles varying densityScales to 10⁶ rowsNeeds scalingMain weakness
Z-score / IQRUnivariateNoYesn/aIgnores correlation; masking (z-score)
Mahalanobis / GMMMultivariatePartly (GMM)YesYesAssumes elliptical/Gaussian shape; Σ⁻¹ unstable if p large
k-NN distanceUnsupervisedNoNo (O(n²))YesGlobal threshold, slow
LOFUnsupervisedYesNoYesk-sensitive, no natural score cut-off
Isolation ForestUnsupervisedPartlyYesNoStruggles with local and axis-oblique anomalies
One-class SVMNoveltyPartlyNoYesν, γ tuning; needs clean training data
AutoencoderNoveltyYesYes (GPU)YesData-hungry, opaque, can learn to rebuild anomalies too
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
from sklearn.preprocessing import RobustScaler
from sklearn.metrics import average_precision_score, classification_report

X_train, X_test, y_test = load_txn_features()      # y_test: 1 = fraud

iso = IsolationForest(n_estimators=300, contamination=0.005,
                      max_samples=256, random_state=42).fit(X_train)
score_iso = -iso.score_samples(X_test)             # higher = more anomalous
print("PR-AUC (IF):", average_precision_score(y_test, score_iso))

Xs = RobustScaler().fit_transform(X_test)          # LOF needs scaling
lof = LocalOutlierFactor(n_neighbors=20, contamination=0.005)
pred_lof = lof.fit_predict(Xs)                     # -1 = outlier
score_lof = -lof.negative_outlier_factor_

# threshold by alert budget, not by 0.5
k = int(0.002 * len(score_iso))                    # top 0.2% = analyst capacity
cut = np.sort(score_iso)[-k]
print(classification_report(y_test, (score_iso >= cut).astype(int), digits=4))

Where it is used

Interview questions

Common mistakes

Related topics

Clustering: k-means and hierarchical · Model evaluation metrics · Dimensionality reduction and PCA · Support vector machines and k-nearest neighbours · Naive Bayes and probabilistic models · Machine learning workflow

Open in the Knowledge reader →Find jobs →