ds@mcpanalytics.aiEmail your data and your question and get an answer about your own data, with the method shown.Email your data and question. Get an answer.

Collaborative Filtering: When to Use It for Recommendations

By MCP Analytics Team | Published , updated

You have a spreadsheet with 5,000 users and their ratings for 200 products. Your boss wants personalized recommendations by next week. You Google "recommendation engine" and get buried in academic papers about matrix factorization, singular value decomposition, and neural collaborative filtering. This guide walks through a way to suggest items from user activity.

Let me walk you through this step by step. We're going to start with a simple approach, finding similar users and recommending what they liked, and build from there. No PhD required.

Worked Example (Simulated): What Might User_1 Rate Item C?

Question: What might User_1 rate item C?

Inputs: Simulated data, seed 17. The table has ratings for items A to D. A dash means no rating. The pattern of which items each user rated is typed in by hand in the script. Only the rating values are random.

Method: Compare User_1 and User_2 on the items both rated. Cosine similarity is a score for how alike their ratings are. Use User_2's rating for C as a guess for User_1.

import numpy as np

seed = 17
rng = np.random.default_rng(seed)
# The rated-item pattern is typed by hand; only rating values are random.
known = np.array([
    [1, 1, 0, 0],
    [1, 1, 1, 0],
    [0, 1, 1, 1],
    [1, 1, 0, 1],
], dtype=bool)
ratings = rng.integers(1, 6, size=known.shape).astype(float)
ratings[~known] = np.nan

print(f"Simulated data, seed {seed}")
print("Columns: A B C D")
for i, row in enumerate(ratings):
    shown = ["-" if np.isnan(x) else str(int(x)) for x in row]
    print(f"User_{i + 1}: " + " ".join(shown))

# Compare User_1 and User_2 on shared items.
# Use User_2's C rating as a one-user guess.
a, b = ratings[0], ratings[1]
shared = ~np.isnan(a) & ~np.isnan(b)
x, y = a[shared], b[shared]
similarity = float(np.dot(x, y) / (np.linalg.norm(x) * np.linalg.norm(y)))
prediction = float(ratings[1, 2])
print(f"Shared items for User_1 and User_2: {int(shared.sum())}")
print(f"Cosine similarity on shared ratings: {similarity:.3f}")
print(f"User_2 rating for C: {prediction:.0f}")
print(f"Predicted rating for User_1 on C (single neighbor): {prediction:.1f}")

Printed output:

Simulated data, seed 17
Columns: A B C D
User_1: 4 5 - -
User_2: 3 3 4 -
User_3: - 2 3 2
User_4: 5 3 - 4
Shared items for User_1 and User_2: 2
Cosine similarity on shared ratings: 0.994
User_2 rating for C: 4
Predicted rating for User_1 on C (single neighbor): 4.0

Result: They share 2 ratings. Their cosine score is 0.994, but with only 2 shared ratings, a score this high is not strong evidence that the two users agree. User_2 rated C as 4, so the one-user guess for User_1 is 4.0.

Limit: This guess uses one other user. More users may rate C in a different way. Simulated data may not show how this works for real users.

Sources

What Collaborative Filtering Actually Means (In Plain English)

Before we jump into methodology, let's make sure we're on the same page about what collaborative filtering is.

Imagine you're at a bookstore. You loved "The Martian" by Andy Weir. The bookseller says, "People who bought that also loved 'Project Hail Mary.'" That's collaborative filtering. You're getting recommendations based on what similar readers enjoyed, not based on book genres or author similarities.

Collaborative filtering finds patterns in user behavior. It answers one fundamental question: If User A and User B liked the same things in the past, what else might they both enjoy?

There are two main flavors:

Both approaches work. We'll focus on user-based first because the logic is more intuitive, then I'll show you when to switch to item-based.

Why This Matters for Your Business

Collaborative filtering uses what users did to suggest items to other users. You can try it on a small table, but few ratings give unsure scores, as the worked example above shows.

Step 1: Structure Your Data (The User-Item Matrix)

Every collaborative filtering project starts with the same data structure: a user-item matrix. Let's build one together.

Here's what your raw data probably looks like: a transaction log or ratings table:

User ID Product ID Rating
User_1 Product_A 5
User_1 Product_B 3
User_2 Product_A 4
User_2 Product_C 5

We need to transform this into a matrix where rows are users, columns are items, and cells contain ratings:

User Product_A Product_B Product_C Product_D
User_1 5 3 n/a n/a
User_2 4 n/a 5 n/a
User_3 5 4 4 2
User_4 n/a n/a 5 4

Notice all those blanks (shown as n/a)? That's normal. Most users haven't rated most items. This is called a sparse matrix, and it's the defining characteristic of collaborative filtering data.

What If You Don't Have Explicit Ratings?

No star ratings? No problem. You can use implicit feedback:

Implicit feedback can be noisier than explicit ratings (someone might click by accident), but many businesses have more of it than they have star ratings. It is often handled differently from star ratings, since a missing action is not the same as a dislike. The Hu, Koren and Volinsky paper in Sources is on this topic.

Quick Data Quality Check

Before moving forward, calculate your interaction density: divide the number of filled cells by total cells (users × items). Density is one summary of the table. Check how many users share ratings on candidate items, then test the method on held-out data. You need overlap between users to find similarities. Consider starting with a subset of your most active users and most popular items to increase density.

Step 2: Calculate User Similarity (Finding Your User's Twins)

Now comes the core of collaborative filtering: measuring how similar users are to each other.

Let's say we want to recommend products to User_1. We need to find users who rated things similarly. A widely used similarity metric is cosine similarity.

Cosine Similarity: The Geometry of Taste

Think of each user as a vector in multi-dimensional space. Each dimension represents a product. The value in that dimension is the user's rating.

Cosine similarity measures the angle between two vectors. If two users have similar taste, their vectors point in the same direction (small angle = high similarity). If they have opposite taste, vectors point in opposite directions (large angle = low similarity).

The formula looks scary, but the concept is simple:

cosine_similarity(User_A, User_B) = (dot_product of ratings) / (magnitude_A × magnitude_B)

Cosine similarity ranges from -1 to 1:

Worked by Hand (Made-up Ratings)

Let's calculate similarity between User_1 and User_3 using the Step 1 matrix above (these are made-up ratings):

User_1 ratings: Product_A = 5, Product_B = 3
User_3 ratings: Product_A = 5, Product_B = 4

We only compare products both users rated (A and B).

Dot product = (5 × 5) + (3 × 4) = 25 + 12 = 37

Magnitude of User_1 = sqrt(5² + 3²) = sqrt(25 + 9) = sqrt(34) = 5.83
Magnitude of User_3 = sqrt(5² + 4²) = sqrt(25 + 16) = sqrt(41) = 6.40

Cosine similarity = 37 / (5.83 × 6.40) = 37 / 37.31 = 0.99

User_1 and User_2 share only Product_A (5 and 4). With one shared rating, cosine similarity is always 1.00, whatever the two numbers are, so that score carries no information about taste.

A similarity of 0.99 looks like nearly identical taste, but it rests on only two shared ratings, so treat it as unsure. With more overlap, whatever User_3 likes (but User_1 hasn't tried yet) becomes a stronger candidate to suggest to User_1.

The Overlap Problem

What if two users only share one product rating? Technically, you can calculate similarity, but it's not meaningful. Set an overlap rule by testing on held-out data. Treat a score based on few shared ratings as unsure. This keeps chance matches from dominating your recommendations.

Alternative Similarity Metrics

Cosine similarity is popular, but not the only option:

Cosine similarity is a reasonable first metric to try. It is simple to compute and is often used on sparse rating data, but compare it with the other metrics on held-out data before you settle on one.

Step 3: Generate Predictions (Weighted Averages That Work)

You've found User_1's similar users. Now what? You need to predict what User_1 would rate for products they haven't seen yet.

The logic is beautifully simple: take a weighted average of how similar users rated that product.

The Prediction Formula

Let's predict User_1's rating for Product_C (which they haven't rated yet).

From our similarity calculations:

Weighted prediction formula:

Predicted rating = Σ(similarity × rating) / Σ(similarity)

For Product_C:
Predicted rating = [(0.99 × 4) + (1.00 × 5)] / (0.99 + 1.00)
                 = [3.96 + 5.00] / 1.99
                 = 8.96 / 1.99
                 = 4.50 stars

With these made-up ratings the weighted guess for User_1 on Product_C is about 4.5 stars. Only two other users rated Product_C, and one of the two similarity scores rests on a single shared rating, so treat this as a rough guess, not a firm prediction.

Accounting for User Rating Bias

Some users are generous raters (average rating: 4.5 stars). Others are critics (average rating: 2.5 stars). If you ignore this, your predictions will be skewed.

The solution: center ratings around each user's mean.

Adjusted formula:

Predicted rating = User_A_mean + [Σ(similarity × (rating - User_mean)) / Σ(similarity)]

This subtracts each similar user's mean rating from their actual rating (capturing how much they liked it relative to their baseline), then adds back User_1's mean rating to get a prediction on User_1's scale.

From the Step 1 matrix, User_1's average rating is 4.0 (5 and 3), User_3's is 3.75 (5, 4, 4 and 2), and User_2's is 4.5 (4 and 5).

Adjusted prediction = 4.0 + [(0.99 × (4 - 3.75)) + (1.00 × (5 - 4.5))] / (0.99 + 1.00)
                    = 4.0 + [(0.99 × 0.25) + (1.00 × 0.5)] / 1.99
                    = 4.0 + 0.7475 / 1.99
                    = 4.0 + 0.38
                    = 4.38 stars

The adjusted guess (4.38) is a little lower than the unadjusted 4.50. User_2's 5 is only half a star above their own average of 4.5, so it counts for less once each rater's baseline is removed. The same caution applies: two neighbors, one with a single shared rating.

Step 4: Rank and Recommend (Turning Predictions Into Action)

You've calculated predicted ratings for all products User_1 hasn't seen. Now you need to decide what to actually recommend.

Top-N Recommendations

The simplest approach: rank products by predicted rating and recommend the top 5 or top 10.

But wait. There's a catch. High predicted ratings often go to popular items that everyone likes. You might end up recommending the same bestsellers to everyone.

Balancing Relevance and Diversity

Good recommendation systems balance:

Here's a practical ranking strategy:

  1. Filter candidates: Only consider items with predicted rating ≥ 4.0 (or your threshold)
  2. Boost diversity: Group items by category, include at least one from each category
  3. Add exploration: Include 1-2 items from less popular categories or new arrivals
  4. Apply business rules: Promote items with higher margins, in-stock inventory, or seasonal relevance

The Exploration-Exploitation Tradeoff

Should you always recommend items with the highest predicted rating (exploitation) or sometimes show wild-card items to learn user preferences (exploration)? Treat this mix as an example start. Track user response and adjust it to your goal. Track which exploratory recommendations work, if users engage with them, update your model accordingly.

Step 5: Evaluate and Iterate (How to Know If It's Working)

You've built a recommendation engine. But is it any good? Let's measure that.

Offline Evaluation (Before You Go Live)

Split your data: build the model on most of it and hold out the rest to test predictions.

Key metrics:

Online Evaluation (The Real Test)

Offline metrics don't tell the whole story. You need to measure actual user behavior:

Run A/B tests: show half your users collaborative filtering recommendations, half your users a baseline (popular items or random items). Measure the difference in conversion and revenue.

When to Retrain Your Model

User preferences change. Inventory changes. Seasonal trends emerge. Your model needs regular updates.

Retrain when:

Set an alert using a chosen baseline and time span. Check the trend before you retrain.

User-Based vs Item-Based: When to Switch Approaches

So far, we've focused on user-based collaborative filtering (find similar users, recommend what they liked). But item-based collaborative filtering can be easier to run in production. Let me explain when to use each.

Item-Based Collaborative Filtering

Instead of finding similar users, you find similar items. If a user liked Product_A, recommend products similar to Product_A.

Item similarity is calculated the same way as user similarity, but you flip the matrix. Now rows are items, columns are users, and cells contain ratings.

Why item-based can be easier to run:

Decision Framework

Use User-Based When... Use Item-Based When...
You have more items than users You have more users than items
Item catalog changes frequently Item catalog is stable
Users have consistent preferences User preferences change often
Real-time personalization needed Pre-computed recommendations okay

Item-based is a common choice for e-commerce and content platforms. For social networks or niche communities with stable users, user-based can suit better.

Matrix Factorization: When Simple Similarity Isn't Enough

User-based and item-based collaborative filtering work well with dense data. But when most of your matrix is empty, they can struggle.

Matrix factorization solves this by finding latent factors: hidden patterns that explain user preferences.

The Intuition Behind Matrix Factorization

Imagine you're predicting movie ratings. Users and movies have underlying characteristics:

To predict a rating, multiply the user vector by the movie vector:

Predicted rating = (0.9 × 0.6) + (-0.3 × 0.1) + (0.7 × 0.9)
                 = 0.54 - 0.03 + 0.63
                 = 1.14 (on a normalized scale)

The magic: you don't manually define these factors. The algorithm learns them from the data.

When to Use Matrix Factorization

Matrix factorization (techniques like SVD, ALS, NMF) can work better when:

Start with simple user-based or item-based collaborative filtering. If performance plateaus, graduate to matrix factorization.

Don't Start with Deep Learning

Neural collaborative filtering and deep learning recommendation systems sound impressive. But they need a lot of data and expertise to tune. Start with the methods in this article. Explore deep learning only if you have very large data and a team to tune it.

The Cold Start Problem (And How to Handle It)

Collaborative filtering has an Achilles heel: it needs data to work. What do you recommend to:

This is the cold start problem. Here's how to handle it.

For New Users

Option 1: Onboarding questionnaire
Ask new users to rate 5-10 items during signup. "Tell us your favorites" builds an instant profile.

Option 2: Demographic defaults
Until you have user-specific data, recommend based on demographic group (age, location, gender). Crude but better than nothing.

Option 3: Popular items
Show trending or bestselling items. Most new users expect this anyway.

For New Items

Option 1: Content-based filtering
Use item attributes (category, brand, price, description) to find similar items. Recommend the new item to users who liked those similar items.

Option 2: Exploration sampling
Show the new item to a random sample of users. Track who engages. Use that initial feedback to start collaborative filtering.

Option 3: Hybrid model
Combine collaborative filtering (when you have data) with content-based filtering (when you don't). Weight each method based on data availability.

Putting It All Together: Your Implementation Checklist

You've learned the methodology. Now let's make sure you're ready to implement.

5-Step Implementation Checklist

  1. Data preparation: Build user-item matrix, handle missing values, check interaction density
  2. Similarity calculation: Compute user-user or item-item similarity using cosine similarity, set an overlap rule from held-out tests
  3. Prediction generation: Calculate weighted predictions, adjust for user rating bias, set minimum confidence threshold
  4. Recommendation ranking: Sort by predicted rating, apply diversity filters, add an exploration component
  5. Evaluation and monitoring: Measure offline metrics (RMSE, precision@K), track online metrics (CTR, conversion), retrain on a schedule you set

Common Implementation Mistakes to Avoid

Your turn

Bring your own data and the question you actually need answered.

MCP AnalyticsData science by email Send us your data and your question, and we will reply. ds@mcpanalytics.ai

Frequently Asked Questions

What's the difference between collaborative filtering and content-based filtering?

Collaborative filtering recommends items based on what similar users liked (user behavior patterns). Content-based filtering recommends items similar to what you've already liked (item characteristics).

Think of it this way: collaborative filtering says "People like you enjoyed this," while content-based says "This is similar to things you've enjoyed." Most modern systems use both approaches together: collaborative filtering for personalization, content-based for handling new items and cold start problems.

How much data do I need to start using collaborative filtering?

You need users who rated some of the same items. The more overlap, the steadier the scores.

If you have fewer users, start with item-based collaborative filtering (it's less sensitive to sparse data) or use content-based filtering until your user base grows. Density is one summary of the table. Check how many users share ratings on candidate items, then test the method on held-out data.

What do I do about the cold start problem?

The cold start problem happens when you have new users with no interaction history or new items with no ratings.

For new users, ask them to rate 5-10 items during onboarding to build an initial profile. For new items, use content-based recommendations (recommend to users who liked similar items) or promote them to a diverse sample of users to gather initial feedback. You can also use hybrid approaches that combine collaborative filtering with demographic or content data to bridge the gap until you have enough interaction history.

Should I use user-based or item-based collaborative filtering?

Item-based collaborative filtering can be easier to run in production. Here's why: items change less frequently than user preferences, so you can pre-compute item similarities and cache them. With user-based filtering, you need to recalculate user similarities constantly as preferences change.

Use item-based unless you have a stable user base with changing inventory (like a news site where articles change daily but readers are consistent). Item-based is a common choice for e-commerce, streaming, and content platforms.

How do I measure if my recommendations are actually working?

Track both offline and online metrics. Offline: use metrics like precision@k, recall@k, and RMSE on held-out test data to evaluate prediction accuracy. Online: measure click-through rate (CTR), conversion rate, and average order value for recommended items.

But the most important metric is whether users engage with recommendations over time. If CTR on recommendations drops after initial curiosity, your model needs improvement. Run A/B tests comparing your collaborative filtering recommendations against a baseline (popular items or random) to measure the true incremental lift in conversion and revenue.