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 99/ 160
05. Classical Machine Learning

Recommendation Systems (Collaborative & Content-Based)

Build recommenders with collaborative filtering, content features, and hybrid strategies.

AdvancedCollaborative · Content-Based3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

A recommender finds items you'll probably like by looking at what similar people liked, or at items similar to ones you already enjoyed.

Think of it like…

A knowledgeable shop assistant: they remember what people like you bought (collaborative), know what's in the shop and what you've liked before (content-based), and when you're new they suggest bestsellers until they learn your taste (cold start).

Where you’ve seen it

A marketplace has 1,000,000 users, 100,000 items and 20 million interactions, so the user-item matrix is 20,000,000 / 10¹¹ = 0.02% dense; stored densely as 4-byte floats it would take 400 GB, but as a sparse matrix it needs only the 20 million entries. Item-item collaborative filtering compares rating vectors: item A rated by four users as [5, 3, 0, 1] and item B as [4, 0, 0, 1] have cosine similarity (20 + 0 + 0 + 1) / (√35 × √17) = 21 / 24.39 = 0.861. A matrix-factorisation model with 2 latent factors gives a user vector [1.2, 0.5] and an item vector [0.9, 1.4], so the predicted preference is 1.2 × 0.9 + 0.5 × 1.4 = 1.78. For ranking quality, suppose the top-5 list has relevant items at ranks 1, 3 and 5: precision@5 = 3/5 = 0.6, DCG = 1/log₂2 + 1/log₂4 + 1/log₂6 = 1 + 0.5 + 0.387 = 1.887, ideal DCG = 1 + 0.631 + 0.5 = 2.131, so NDCG@5 = 0.886. The team evaluates with a time-based split (train on weeks 1 to 8, test on week 9), compares with a popularity baseline and validates winners in an online A/B test.

Words you’ll hear

Collaborative filtering
Recommending from patterns in user-item interactions.
Matrix factorisation
Learning user and item latent vectors whose dot product predicts preference.
Cold start
Having too little data about a new user or item to personalise.
NDCG@k
A ranking metric that rewards placing relevant items near the top.

Visual diagram

Loading interactive diagram

Theory & deep dive

Collaborative, content-based and hybrid methods

Memory-based collaborative filtering computes similarities directly: user-user (people who behaved like you) or item-item (items consumed by the same users). Item-item with cosine similarity, for example cos(A, B) = Σ aᵢbᵢ / (‖a‖‖b‖) = 21 / (5.916 × 4.123) = 0.861 for the rating vectors [5, 3, 0, 1] and [4, 0, 0, 1], is stable, easy to explain ("because you viewed X") and works well when items change more slowly than users. It costs O(n²) similarities, so production systems use approximate nearest neighbours. Matrix factorisation approximates the sparse rating matrix R ≈ P Qᵀ with k latent factors (k = 32 to 256 in practice) trained by SGD or ALS, minimising squared error on observed entries plus L2 regularisation; for implicit feedback (clicks, plays) use confidence-weighted ALS or BPR with negative sampling, since the absence of an interaction isn't a dislike.

Content-based methods represent items by attributes (genre, text embedding, price) and users by the average of items they liked, scoring by similarity; they handle new items immediately and explain themselves, but they over-specialise (recommending more of the same) and need good features. Hybrids combine signals: add content features to factorisation models (LightFM), use two-tower neural networks that embed users and items for retrieval, or stack collaborative scores with content and context features in a learning-to-rank model. Cold start: for new users use popularity, onboarding questions and context (device, location); for new items use content features and exploration (bandits) so they get a chance to collect feedback.

Factorisation prediction

User vector p = [1.2, 0.5], item vector q = [0.9, 1.4]. Predicted preference = p·q = 1.2 × 0.9 + 0.5 × 1.4 = 1.08 + 0.70 = 1.78. Training adjusts these vectors so predictions on observed interactions match actual feedback.

Key takeaway: Use similarity or factorisation for collaborative signal, content features for cold start, and combine them in a hybrid two-stage system.

Evaluation, biases and production concerns

Evaluate with a time-based split (train on the past, test on later interactions) or leave-last-out per user, never a random split of interactions, which leaks future behaviour. Use ranking metrics at the list length users see: precision@k, recall@k, MAP, and NDCG@k (NDCG = DCG / ideal DCG, with DCG = Σ relᵢ / log₂(i + 1): relevant items at ranks 1, 3 and 5 give DCG 1.887 against an ideal 2.131, so NDCG@5 = 0.886), plus coverage, diversity, novelty and fairness measures. Always compare with a popularity baseline and a simple item-item model: complex models often win by only a few points. Offline metrics are only a proxy, since logged data reflects what the old system chose to show (exposure bias), so confirm winners with an online A/B test on engagement, conversion and long-term retention.

Watch for popularity bias (rich-get-richer recommendations), feedback loops (the model's own recommendations shape the data it learns from), filter bubbles, position bias in click data (use inverse-propensity weighting or randomised exploration), and business constraints (inventory, margins, safety, already-purchased items). Production concerns: latency (precompute candidate sets, use an ANN index, and rank a few hundred items within tens of milliseconds), freshness (incremental updates of embeddings or session-based models that use the last few clicks), explainability ("because you watched ..."), privacy and the cost of retraining. Start simple (popularity, item-item, ALS), measure, then add complexity only when the lift justifies it.

NDCG by hand

Top-5 relevant at ranks 1, 3, 5: DCG = 1/log₂2 + 1/log₂4 + 1/log₂6 = 1 + 0.5 + 0.387 = 1.887. Ideal (ranks 1, 2, 3): 1 + 0.631 + 0.5 = 2.131. NDCG@5 = 1.887 / 2.131 = 0.886. Precision@5 = 3/5 = 0.6.

Key takeaway: Use time-based splits and ranking metrics, beat popularity, and mind exposure bias, feedback loops and latency.

How it works, step by step

Step 1 of 4
Analyst

1. Define the goal and data

Choose what to optimise (clicks, purchases, retention), build the interaction table and decide explicit versus implicit feedback.

20M interactions · 0.02% dense
Key numbers at this step
Store
sparse matrices

When to use it & trade-offs

What it is

A recommender system predicts which items a user is likely to want and ranks them. The main families are collaborative filtering (use the behaviour of similar users or similar items: user-based, item-based and matrix factorisation, which learns low-dimensional user and item vectors whose dot product predicts the preference), content-based filtering (match item attributes to a user profile) and hybrid systems that combine both and add context. Real systems are usually two-stage: a cheap candidate generator retrieves hundreds of items (nearest neighbours in an embedding space), then a ranker scores them with richer features. Data is sparse and often implicit (clicks, views, purchases) rather than explicit ratings.

Why it matters: Recommendations drive a large share of engagement and revenue on commerce, media and marketplace products, and they illustrate many core ML issues in one place: extreme sparsity, cold start, implicit feedback, offline versus online evaluation, popularity bias and feedback loops. A data scientist who can build a sensible baseline, evaluate it correctly (time-based splits, ranking metrics) and reason about trade-offs is valuable.

When to reach for it

  • Product, content and people recommendations
  • Personalised ranking in feeds and search
  • Cross-sell and next-best-action

When to avoid or be careful

  • Random train-test splits of interactions
  • Treating missing interactions as dislikes
  • Skipping the popularity baseline

Recommendation approaches

Item-item collaborative filtering
Best for: Explainable "people who liked this also liked"

Strengths: Simple, stable, easy to explain.

Watch out: Struggles with sparse items and new items.

Matrix factorisation or two-tower models
Best for: Large-scale personalised retrieval

Strengths: Compact embeddings; captures latent taste.

Watch out: Cold start; needs tuning and implicit-feedback care.

Content-based and hybrid
Best for: New items and cold start

Strengths: Works without interaction history; flexible.

Watch out: Over-specialisation; needs good features.

Interview signals & numbers to know

When this topic comes up

  • “Recommend items to users”
  • Cold start
  • Implicit feedback
  • NDCG and precision@k
  • Two-tower and ALS

Benchmarks & rules of thumb

0.02% -
density of 20M interactions in a 1M × 100k matrix
0.861 -
cosine similarity of the two item rating vectors
NDCG@5 = 0.886 -
ranking quality for relevant items at ranks 1, 3, 5

Common mistakes & follow-ups

Common interview mistakes

  • Evaluating offline on a random split and overstating gains.
  • Ignoring popularity bias so the long tail never gets exposure.
  • Shipping a complex model that barely beats the item-item baseline.

Likely interviewer follow-ups

  • How would you handle cold start for new users and items?
  • How do you evaluate a recommender offline?
  • What are exposure bias and feedback loops?
Interview tip: Name the popularity baseline and a time-based split up front. It shows you evaluate recommenders honestly.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Recommendation Systems (Collaborative & Content-Based) with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Anomaly & Outlier Detection (Isolation Forest)
Next topic
Time-Series Forecasting (ARIMA, SARIMA, Prophet)