Recommendation System
Machine Learning
Data Science
AI Applications
Recommender Algorithms

How to build a simple recommendation system?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

A recommendation system suggests items a user is likely to care about, such as movies, books, or products. You do not need a massive production stack to learn the core idea; a small user-item matrix and a similarity measure are enough to build a useful first version.

Pick a Simple Strategy First

There are many recommender approaches, but for a beginner-friendly implementation, item-based collaborative filtering is a good starting point. The basic idea is:

  • Collect user ratings
  • Represent them as a matrix
  • Measure similarity between items
  • Recommend items similar to what the user already liked

This avoids training a heavy model and makes the logic easy to inspect.

Prepare the Ratings Data

Suppose you have a table with user_id, item, and rating.

python
1import pandas as pd
2
3ratings = pd.DataFrame(
4    [
5        (1, "Book A", 5),
6        (1, "Book B", 3),
7        (1, "Book C", 4),
8        (2, "Book A", 4),
9        (2, "Book B", 2),
10        (2, "Book D", 5),
11        (3, "Book A", 2),
12        (3, "Book C", 5),
13        (3, "Book D", 4),
14        (4, "Book B", 5),
15        (4, "Book C", 3),
16        (4, "Book D", 4),
17    ],
18    columns=["user_id", "item", "rating"],
19)
20
21matrix = ratings.pivot_table(
22    index="user_id",
23    columns="item",
24    values="rating"
25).fillna(0)
26
27print(matrix)

This produces a user-item matrix where each row is a user and each column is an item.

Compute Item Similarity

Once you have the matrix, compute similarity between item columns. Cosine similarity is common because it compares rating patterns rather than raw magnitude.

python
1from sklearn.metrics.pairwise import cosine_similarity
2
3item_matrix = matrix.T
4similarity = cosine_similarity(item_matrix)
5
6similarity_df = pd.DataFrame(
7    similarity,
8    index=item_matrix.index,
9    columns=item_matrix.index,
10)
11
12print(similarity_df.round(2))

If Book A and Book C have similar rating patterns across users, their similarity score will be high.

Generate Recommendations for One User

Now recommend items for a target user by looking at what they rated highly and pulling similar items they have not rated yet.

python
1def recommend_items(user_id, top_n=3):
2    user_ratings = matrix.loc[user_id]
3    liked_items = user_ratings[user_ratings >= 4].index
4
5    scores = {}
6    for liked in liked_items:
7        for item, score in similarity_df[liked].items():
8            if item not in liked_items and user_ratings[item] == 0:
9                scores[item] = scores.get(item, 0) + score
10
11    ranked = sorted(scores.items(), key=lambda pair: pair[1], reverse=True)
12    return ranked[:top_n]
13
14print(recommend_items(1))

This is a deliberately small implementation, but it demonstrates the core loop used by larger systems: infer preference from similar behavior.

Improve the Baseline

A simple recommender can be useful, but real data is messy. Once the baseline works, typical improvements include:

  • Ignore very unpopular items with too little data
  • Normalize ratings so generous and strict users are more comparable
  • Add content features such as genre, category, or tags
  • Separate training data from evaluation data

If you later outgrow pure collaborative filtering, you can move to matrix factorization or hybrid recommenders. The important part is to start with something you can validate.

Evaluating Whether It Works

Do not judge a recommendation system only by whether the code runs. You need an evaluation plan. A common approach is to hide one known user interaction and see whether the system recommends that item back.

For explicit ratings, you can also compute ranking metrics or prediction error. Even a simple offline check is far better than guessing.

python
1def held_out_example():
2    train = ratings.iloc[:-1]
3    test = ratings.iloc[-1]
4    print("Held-out row:")
5    print(test)
6
7held_out_example()

In production, you would also measure click-through rate, conversion rate, or watch time depending on the product.

Common Pitfalls

The most common mistake is treating missing ratings as genuine dislike. In most datasets, a missing value means the user never interacted with the item, not that they rejected it.

Another mistake is overfitting to tiny data. If only two users rated an item, a high similarity score may be misleading. Add minimum-support rules before trusting the output.

A third mistake is skipping evaluation. Recommendation systems can produce plausible-looking results that are actually weak. Always test with held-out data or online metrics.

Summary

  • A simple recommendation system can be built from a user-item ratings table and cosine similarity.
  • Item-based collaborative filtering is easy to understand and implement.
  • Start with a pivoted ratings matrix, compute similarities, then rank unseen items.
  • Missing ratings should be treated carefully because they are not always negative feedback.
  • Validate the system with held-out data before trusting the recommendations.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.