Specialized Classical ML: Anomaly Detection, RecSys & Learning to Rank
Isolation Forests & Local Outlier Factor, Collaborative Filtering & Matrix Factorization (ALS/SVD), Two-Tower Retrieval → Ranking funnels, and NDCG@K / MAP / MRR.
Specialized classical ML extends beyond standard classification into Isolation Forests for outlier detection, Collaborative Filtering for recommendations, and Learning to Rank for search.
Real products like Netflix feeds, fraud radars, and search engines cannot be framed as simple binary classification—they require ranking and unsupervised anomaly scoring.
Recommendations, Search Ranking, and Anomaly Detection drive the core revenue of Netflix, Amazon, YouTube, Stripe, and Google!
You CANNOT run a heavy XGBoost or neural ranker over 10 million products in 50 ms — understanding Two-Stage Retrieval (ANN / Two-Tower) → Ranking (LambdaMART / NDCG) is the #1 ML System Design blueprint!
Knowing how to handle cold-start users, implicit feedback (clicks vs. explicit stars), and position bias separates production RecSys from toy MovieLens notebooks.
Top ML System Design loop: 'Design a real-time recommendation or fraud anomaly system — how do you handle cold-start, train on implicit clicks, and evaluate with NDCG@10?'
Why does Isolation Forest isolate an extreme anomaly in 1–2 random axis cuts while a normal point takes ~10 cuts?
- Explain how Isolation Forest isolates outliers via short random-tree path lengths h(x) in O(N) time
- Contrast Content-Based Filtering, User/Item Collaborative Filtering, and Matrix Factorization (R ≈ U Vᵀ)
- Design a production Two-Stage RecSys architecture (Fast Candidate Retrieval → Heavy GBDT/Neural Ranker)
- Compute and optimize Learning-to-Rank metrics: Precision@K, Recall@K, MRR, and NDCG@K
This chapter unites three of the highest-impact applied ML pillars: spotting the 1 needle in a haystack (Isolation Forest / LOF), predicting what a user will love next (Matrix Factorization & Two-Stage RecSys), and ordering the top 10 results so the best answer lands at Rank #1 (NDCG@K)!
1. Unsupervised Anomaly Detection: Isolation Forest, LOF & One-Class SVM
Traditional anomaly detectors try to draw a tight boundary around 'normal' points — which explodes in high dimensions. Isolation Forest flips the problem upside down: pick a random feature and a random split value recursively. Outliers get isolated in just 1–2 cuts! Test the scoring formula live below.
Choosing an Anomaly Detector
- Isolation Forest: fast, handles high dimensions & tabular data out-of-the-box — #1 production default!
- Local Outlier Factor (LOF): Compares a point's local density to its K neighbors — catches local anomalies sitting near a dense cluster even when they aren't global extremes.
- One-Class SVM / Elliptic Envelope: Great for clean small-to-medium datasets when normal data forms a tight unimodal shape.
Random Cut #1: Anomaly Isolated in 2 Cuts vs. Normal Cluster Needing 8+!
2. Recommender Systems: Collaborative Filtering, Matrix Factorization & Cold-Start
A user-item rating matrix is typically 99.9% empty. Matrix Factorization discovers hidden latent tastes (e.g., Sci-Fi, Dark Humor, 90s Indie) as compact -dimensional vectors and so predicted affinity is just a fast dot product !
Solving Real-World RecSys Challenges
- Explicit vs. Implicit Feedback: Most platforms only observe clicks/watches (no negative 1-star ratings!). Use Weighted ALS or BPR (Bayesian Personalized Ranking) with negative sampling.
- Cold-Start Problem: New users/items have zero interaction history → fall back to Content-Based features (metadata, text/image embeddings) or Two-Tower neural models that encode side features directly into embeddings!
3. Two-Stage Retrieval → Ranking & Learning to Rank (NDCG@K)
Production search and feed engines run in two stages: (1) Retrieval narrows 10M items to ~500 candidates in 10 ms via ANN vector search (Ch 10); (2) Ranking scores those 500 candidates with rich cross-features using GBDT (LambdaMART) to maximize NDCG@K!
Pointwise vs. Pairwise vs. Listwise Ranking
- Pointwise: Predict click probability per item independently (ignores relative order!).
- Pairwise (RankNet / LambdaRank): Optimize pairs so relevant item scores higher than irrelevant item .
- Listwise (LambdaMART): Directly weights pairwise gradients by — focusing maximum optimization power on the top of the page!
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
MRR (Mean Reciprocal Rank) only cares about the rank of the FIRST relevant item (1/rank) — great for single-answer QA/search. NDCG@K handles graded relevance (0, 1, 2, 3) across ALL top-K positions — standard for feeds and e-commerce!
Reorder Search Results & Maximize NDCG@4 to 1.000
Real-Time Payment & Cloud Anomaly Alerts
Isolation Forest flags abnormal API spikes or card transactions with zero labeled attacks.
E-Commerce & Video Feeds
Two-Tower Retrieval + LightGBM LambdaMART Ranker + Diversity Re-ranking.
from sklearn.ensemble import IsolationForest
from sklearn.metrics import ndcg_score
import numpy as np
# 1. Unsupervised Isolation Forest anomaly detector
iso = IsolationForest(n_estimators=200, contamination=0.01, random_state=42)
preds = iso.fit_predict(X_train) # -1 = anomaly, +1 = normal
# 2. Evaluate graded ranking with NDCG@4
true_rel = np.array([[3, 2, 1, 0]])
pred_scores = np.array([[0.95, 0.40, 0.80, 0.10]])
print("NDCG@4:", round(ndcg_score(true_rel, pred_scores, k=4), 4))