Keyboard shortcuts

Press ← or β†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

πŸ“– ⏱️ ~35 min read 🎯 Intermediate

Collaborative Filtering

πŸ“ Before You Continue: Please read first the discussion of "retrieval as the starting point of the three-stage funnel" in Part 1, Section 1.1, and the "retrieval: from billions to thousands" thread in 1.2. This chapter covers the most classic family of methods in the retrieval layer.

When you open a shopping app, how does the system decide "what else you might like"? The most naive yet most powerful intuition comes from Collaborative Filtering (CF): inferring individual preferences from the collective behavior of "people" and "items" β€” people who like the same things tend to have similar tastes; items liked by the same group of people tend to be similar in nature.

The idea of collaborative filtering is nearly as old as recommender systems themselves, but it goes far beyond "finding similar things". From neighborhood-based ItemCF / UserCF, to Swing built for industrial robustness, to matrix factorization mapping users and items into latent vectors, this chapter walks you through the evolution from statistical co-occurrence to vector representation.

After reading this chapter, you will be able to:

  • Compute item and user similarity with cosine similarity / Pearson correlation, and articulate the difference between the two
  • Explain how Swing filters random noise through bipartite-graph substructures, and how Surprise mines complementary items
  • Describe the trade-offs between UserCF and ItemCF regarding user cold start and explainability
  • Describe how matrix factorization (FunkSVD / BiasSVD) alleviates data sparsity with low-rank latent vectors
  • Complete 5 graded practice problems, consolidating the full path from co-occurrence to vectorization

2.1.0 Two Perspectives on Collaborative Filtering

Collaborative filtering can be split along two directions: item-based (ItemCF) asks "what else is similar to the items you liked"; user-based (UserCF) asks "what else do people similar to you like". The former fits industrial scenarios better (item sets are stable and can be precomputed offline), while the latter feels more natural in scenarios with strong social flavor.

Two perspectives of collaborative filtering: the item view and the user view

Whichever perspective you take, the core revolves around one concept β€” co-occurrence: two items interacted with by the same set of users, or two users interacting with the same set of items. The more frequent the co-occurrence, the higher the similarity. As we will see in the next three sections, all CF methods are just different answers to "how to define and exploit co-occurrence".


2.1.1 ItemCF: Item-Similarity-Based Collaborative Filtering

The core idea of ItemCF is that user interests are coherent: people who like an item tend to be interested in similar items. When recommending to a user, the system first identifies the items the user interacted with recently (seed items), then finds the most similar candidates for each seed, and finally aggregates the scores.

Computing Item Similarity

Most real-world scenarios have only implicit feedback (clicks, purchases), no ratings. ItemCF quantifies item similarity with cosine similarity:

where is the total number of users who interacted with item , and is the co-occurrence count of the two items (the number of users who interacted with both). The denominator normalizes the co-occurrence count, preventing popular items from dominating by sheer interaction volume β€” exactly the biggest trap of naive co-occurrence.

Recommending Candidate Items

Given the similarity matrix, the online flow has three steps: β‘  take a few hundred items the user recently interacted with as seeds; β‘‘ find the Top-10 similar items for each seed, quickly generating a large pool of candidates; β‘’ compute the user's interest score for candidate item :

is the set of items the user interacted with, and is the user's interest strength on item (set to 1, or weighted by interaction time/type). Finally, rank all candidates by score and take the Top-N.

🧠 Mental Model: A Borrower's Reading List

Think of items as "books" and users as "borrowers". ItemCF's logic: if Alice borrowed The Three-Body Problem and Ball Lightning, and Bob also borrowed The Three-Body Problem, then the system guesses Bob will probably like Ball Lightning too β€” because these two books are always borrowed by the same crowd. The point is not the content of the books, but "who reads them".

Computational Efficiency Optimizations

Brute-force computation of all item-pair similarities is , but the vast majority of item pairs share no common users, so their similarity is necessarily 0. A user–item inverted index speeds this up dramatically: maintain an interaction list per user, and when traversing, pair up items within each list, accumulate the co-occurrence matrix , then divide by the normalization terms. The optimized complexity is roughly ( is the total number of interactions, the average number of items per user), far below brute force in sparse settings.

Similarity for Rating Data (Pearson Correlation)

When the system has explicit ratings (e.g., 5 stars), the Pearson correlation coefficient is more robust than cosine, because centering removes differences in rating distributions across items:

Based on this, one can predict a user's rating for an unseen item:

In large-scale systems, for computational and sparsity reasons, most still use cosine similarity supplemented with weighted normalization.

Analysis: ItemCF can precompute the full item similarity matrix offline; online it only needs to fetch the Top-N similar items of the seed items, with very low latency and strong explainability. But it is powerless against item cold start (new items have no co-occurrence), and its similarity is fixed, hard to fuse with contextual features. It suits scenarios with stable item sets and dense interactions.


2.1.2 Swing: Similarity Optimization for Industrial Scenarios

ItemCF is naive and effective, but industrial deployment exposes clear problems: popular items dominate results due to high co-occurrence; noise such as random misclicks is treated equally. Swing offers an elegant answer β€” analyze substructures of the user–item bipartite graph to filter noise.

Its core insight: if multiple users bought the same pair of items despite sharing few other co-purchases, then the association between that pair is more trustworthy. In other words, the more "specific" the co-purchase behavior, the greater its contribution to similarity.

Computing Item Similarity

Let and be the sets of users who interacted with items and . For each pair of common users , if they share few other co-purchases (smaller ), then their joint choice of this item pair is more specific and should contribute a higher score:

is a smoothing coefficient preventing tiny denominators from causing numerical instability. To reduce the excessive influence of active users, a user weight is introduced:

Swing's bipartite-graph structure and swing subgraphs

As shown, users A and B have 4 swing subgraphs , , , . If and A and B have 4 other shared behaviors, the user pair contributes ; h and p additionally share t and r, contributing two extra terms, so finally , higher than . Combinations with few but "exclusive" co-occurrences score higher β€” this is exactly how Swing filters popular-item noise.

Surprise: Complementary Item Recommendation

Swing scores already capture associations, but handling complementary items (buying a phone case after a phone) remains hard β€” complementary relations are directional and time-ordered. The Surprise algorithm measures complementary relevance at three levels: category, item, and cluster:

  • Category level: compute conditional probabilities between categories with a user-category matrix, , and adaptively truncate the long tail using the maximum relative drop.
  • Item level: consider purchase order and time interval β€” the closer in time, the stronger the complementarity:

  • Cluster level: run label propagation on a graph of billions of items (edge weights are Swing scores) to cluster and alleviate sparsity, then combine linearly:

Analysis: Swing significantly improves robustness while preserving ItemCF's efficiency, making it an evergreen of industrial I2I retrieval; the cost is building and traversing the bipartite graph, with higher computation than naive ItemCF. Surprise goes further for complementary scenarios, but introduces multi-level hyperparameters and clustering steps, raising engineering complexity.


2.1.3 UserCF: User-Similarity-Based Collaborative Filtering

Mirror to ItemCF, UserCF assumes: users with similar historical behavior will have similar future preferences. It first finds the "neighbors" most similar to the target user, then predicts the target user's interests from the neighbors' behavior.

Computing User Similarity

Given users and with item sets and , three common measures:

  • Jaccard coefficient (implicit feedback only):

  • Cosine similarity (accounting for activity differences):

  • Pearson correlation (with ratings; centering removes rating-habit differences):

UserCF: similar users contribute candidates

Recommending Candidate Items

Select the users with the highest similarity as the neighbor set . A simple weighted average predicts ratings:

The bias-aware version further removes personal habits:

At serving time, find the most similar users for the target user, collect their interacted items as candidates, compute interest scores , rank, and take the Top-N. The optimized complexity is roughly , far below .

Analysis: UserCF excels in scenarios where user interests converge, such as "trending news" or "breaking events", and naturally supports social recommendation through "discovering similar people". But when users vastly outnumber items, computation and storage costs are high, and user cold start is hard (new users have no behavior). In industry, ItemCF is more common, because its item set is stable and can be fully precomputed offline.


2.1.4 Matrix Factorization: From Similarity to Vector Representation

Both UserCF and ItemCF face a fundamental challenge: data sparsity. Real interaction matrices are extremely sparse, leaving too few common ratings to compute reliable similarities. Matrix factorization takes a different route β€” instead of explicitly computing similarities, it learns latent vector representations for users and items, letting distances in the vector space naturally reflect preferences. This marks CF's shift from statistical methods to machine learning methods.

The Dawn of the Latent Vector Era

Matrix factorization rests on two assumptions: the low-rank assumption β€” the seemingly complex rating matrix is actually governed by a few latent factors (such as "male-oriented vs. female-oriented", "serious vs. light"); and the latent vector assumption β€” every user/item can be represented by a vector encoding these factors.

Matrix factorization: capturing users and items in a latent vector space

FunkSVD: The Basic Model

FunkSVD factorizes the rating matrix into a user feature matrix and an item feature matrix. User is represented by a -dimensional vector , item by , and the predicted rating is their inner product:

The optimization objective makes predictions approximate true ratings (over known ratings only):

Update with gradient descent, where the error is :

In practice, add L2 regularization against overfitting: .

🧠 Mental Model: Taste Axes

Plot every user and every movie on a 2D chart: the horizontal axis is "male-oriented ↔ female-oriented", the vertical axis "serious ↔ light". Users who like The Princess Diaries and the movie itself both land in the "female-oriented, light" corner, so the inner product is naturally large. Even if two users have never watched the same movie, as long as they are close on the latent factors, they can recommend for each other β€” this is the key to how vector representation overcomes sparsity.

BiasSVD: The Improved Model

The basic model ignores a fact: some people are naturally generous raters ("pushovers"), others strict; some movies universally rate high due to star casts. BiasSVD introduces bias terms:

is the global average rating, the user bias, the item bias. The optimization objective updates the biases as well:

Analysis: Matrix factorization handles sparse data naturally (two users can be linked through latent factors without any shared rating), and inner-product retrieval is efficient. But it remains a linear model, hard to fuse with side information or complex feature crossings. This leads directly to the two-tower and deep models of later chapters.


⚠️ Common Mistakes in 2.1

#MistakeExampleWhy It's WrongFix
1Using raw co-occurrence counts as similarityPopular items appear "highly similar" to everythingNo normalization in the denominator; popular items dominate by volumeNormalize with cosine similarity dividing by
2Using ItemCF / UserCF interchangeablyForcing UserCF in a user-cold-start scenarioNew users have no history, so UserCF can't find neighborsFor user cold start use ItemCF; for item cold start use attribute/vector methods
3Using Pearson as cosineForcing Pearson in an implicit-feedback settingWithout ratings there is no mean to center onUse cosine for implicit feedback; Pearson only when ratings exist
4Ignoring MF's sparsity preconditionBelieving MF always computes accurate similaritiesWith extremely few interactions, latent vectors are poorly learnedFor sparse data, combine side info (see EGES in Section 2.2) or two-tower models
5Assuming CF can incorporate context"Add time/location features into ItemCF"Neighborhood methods have no feature-crossing channelRepresentation learning (MF/two-tower) is needed to fuse features

Chapter Summary

πŸ“Œ Key Takeaways

ConceptKey PointsWhy It Matters
ItemCF, expand candidates from seed itemsA key industrial I2I retrieval channel, precomputable offline
SwingBipartite-graph specific co-occurrence + user weightsFilters popular-item noise, improves similarity robustness
UserCFAggregate neighbor behavior by user similarityGreat for trending/social scenarios, but user cold start is hard
Matrix Factorization, low-rank latent vectorsOvercomes sparsity, pioneering vectorization
BiasSVDAdds bias termsSeparates systematic biases, notably improving accuracy

❓ FAQ

Q1: When should I use ItemCF vs. UserCF?

A: Use ItemCF when the item set is stable and you need to explain "why this similar item is recommended" (the industrial mainstream); use UserCF when user interests strongly converge (e.g., breaking news) or for social "similar people" recommendation. In user cold-start scenarios, ItemCF is more robust.

Q2: What exactly is the difference between cosine similarity and Pearson correlation?

A: Cosine only looks at the angle between interaction vectors and is affected by absolute item popularity; Pearson first centers (subtracts respective means), removing rating-habit differences between "pushovers vs. strict graders" and focusing on relative trends. Prefer Pearson with rating data; use cosine for implicit feedback.

Q3: Why does matrix factorization handle sparse data better than ItemCF?

A: ItemCF needs two items to share interacting users before similarity can be computed; matrix factorization, through a shared latent-factor space, lets two users with no common ratings recommend for each other via close latent vectors, generalizing to unseen combinations.

πŸ”— Connections to Later Chapters

  • 2.2 (Vector Retrieval I2I) ports sequence modeling (Word2Vec) into similarity learning, and uses item attention to solve MF's difficulty in fusing side info.
  • 2.3 (Two-Tower Model) upgrades MF's inner-product idea to deep-network encoding, enabling efficient U2I retrieval.
  • 2.4 (Sequential Retrieval) further captures temporal interest dynamics ignored by ItemCF/MF.
  • 3.x (Ranking) later applies complex deep models to finely rank the thousands of candidates retrieved in this chapter.

Practice Problems

Work through all problems in order β€” they get progressively harder. Each has a complete solution you can reveal after trying it yourself.


Problem 2.1.1 β€” Similarity Normalization 🟒 Easy

User A has interacted with 100 items, user B with 10 items, and they share 5 common items. Compute the Jaccard coefficient, and explain what would go wrong if you instead used "raw co-occurrence count = 5" as the similarity.

πŸ’‘ Solution (click to reveal)

Approach: Jaccard divides the intersection by the union.

Key points:

  • Using the raw co-occurrence count 5 as similarity, anyone sharing 5 items with A would be judged "equally similar", ignoring the fact that A is extremely active (100 items).
  • Normalization (Jaccard/cosine) lets the "relative overlap ratio" rather than the "absolute co-occurrence count" determine similarity, preventing active users/popular items from dominating.

Problem 2.1.2 β€” ItemCF Scoring 🟒 Easy

User has interacted with items , with interest strengths and . Item has similarity with and with . Compute the user's interest score for candidate item .

πŸ’‘ Solution (click to reveal)

Approach: Apply the ItemCF interest formula .

Key points:

  • The score accumulates linearly with similarity and interest strength; more seeds and higher similarities yield higher candidate scores.
  • This is exactly the core of ItemCF: "take seeds β†’ expand by similarity β†’ aggregate scores".

Problem 2.1.3 β€” The Specificity Intuition of Swing 🟑 Medium

Consider two item pairs and . Users A and B both interacted with both pairs, and A and B's other shared behavior counts are 4 (for h,p) and 2 (for h,t). Let . Suppose has only this single pair of common users, while additionally receives a contribution of the same structure from another common user pair C and D. Compare and , and explain what Swing is trying to filter.

πŸ’‘ Solution (click to reveal)

Approach: Per the Swing formula, each common user pair contributes .

  • : only the A, B pair, .
  • : A, B contribute ; C, D (also ) contribute another ; total .

Wait β€” here is actually higher? Note: Swing's "specificity" means this user pair shares few other behaviors. If A and B overlap only on h and t (few other shared behaviors), while on h and p they also share more items (many shared behaviors = 4), then the h, p association is "not exclusive enough". In the problem, the shared behavior count of h,t (2) is smaller than that of h,p (4), so the per-pair contribution of h,t is larger β€” meaning the co-occurrence of h and t is more specific and more trustworthy.

Key points:

  • Swing penalizes generic users who "buy everything together" via , and boosts "exclusive co-occurrences".
  • What it filters is spurious strong associations caused by random misclicks or generic popular items.

Problem 2.1.4 β€” FunkSVD Gradient Update πŸ”΄ Hard

Given a known rating , current , , , no regularization. Compute by hand and after one gradient descent step (keep 3 decimal places).

πŸ’‘ Solution (click to reveal)

Approach: First compute the prediction and the error.

Update rules: , .

Key points:

  • The error is positive (prediction too low), so parameters shift upward overall, increasing the inner product toward 4.
  • Each dimension's update is proportional to "the counterpart vector's component", reflecting the symmetry of the inner product.

πŸ† Challenge: Design a Retrieval Combination

A short-video platform adds tens of millions of items daily, with an enormous long tail. Write about 150 words explaining how you would combine this chapter's ItemCF, Swing, and matrix factorization as multi-channel retrieval (what each channel is responsible for, how they complement each other), and identify which channel should backstop long-tail new items and why.

πŸ’‘ Hint

ItemCF/Swing handles "behavior-similarity expansion", with Swing suppressing popular-item noise, making it better at mining long-tail associations; matrix factorization handles "latent-vector generalization" to cover sparse users. New items have no co-occurrence, so the CF channels will inevitably miss them β€” the backstop should be a vector channel that can fuse side info (think EGES in 2.2) or a two-tower model. Note this chapter's MF itself also struggles with brand-new items and needs external attributes.