Recommendation systems power many of the digital platforms we use every day. From movie suggestions on Netflix to product recommendations on Amazon, these algorithms help users discover content that matches their interests.

When I first started learning machine learning, recommendation systems were one of the most fascinating topics to me. After experimenting with several datasets and Python libraries, I realized that even a simple recommendation system can produce surprisingly useful results.

In this tutorial, we will build a simple recommendation system using Python and understand the core ideas behind recommendation engines. By the end you will know:

  • What recommendation systems are
  • How collaborative filtering works
  • How to build a movie recommendation system in Python
  • How to use real-world datasets for recommendations

Why Recommendation Systems Are Important

Modern platforms host millions of pieces of content. Without intelligent filtering, users would struggle to find relevant items. Recommendation systems help platforms:

  • Personalize user experiences
  • Increase engagement and time-on-platform
  • Improve content discovery at scale
// NOTE
Research shows that a large percentage of content watched on Netflix comes from recommendations rather than manual searches. Similarly, recommendation algorithms drive a major share of sales generated by Amazon.

Types of Recommendation Systems

There are three main approaches used in modern recommendation systems:

📄
Content-Based Filtering

Recommends items based on similar item features. If a user watches many sci-fi movies, the system suggests other sci-fi titles.

  • Genre
  • Keywords & description
  • Actors or directors
👥
Collaborative Filtering

Recommends items based on similar user behavior. If two users share similar ratings, movies liked by one are suggested to the other.

  • No item metadata needed
  • Scales well with users
  • Powers this tutorial
⚙
Hybrid Systems

Combines both content-based and collaborative filtering for higher accuracy. Used by large-scale platforms like Netflix.

  • Best of both worlds
  • Handles cold start better
  • More complex to implement

Understanding the User–Item Matrix

The foundation of collaborative filtering is the user–item matrix. It represents users as rows, items (movies) as columns, and ratings as values. The goal is to predict the missing ratings (marked ?) and surface relevant recommendations.

Inception The Matrix Interstellar Avatar
User 1 5 4 ? 3
User 2 4 ? 5 ?
User 3 ? 5 4 4
User 4 3 3 ? 5

// rated cells = known data  ·  ? = what the algorithm predicts

Dataset: MovieLens

For this tutorial we use the popular MovieLens dataset, widely used in recommendation system research and ideal for experimenting with collaborative filtering algorithms.

100K+
Ratings
943
Users
1,682
Movies
1–5
Rating scale
// TIP
When I first worked with this dataset, I realized how different real-world data is compared to small classroom examples. The sparsity alone teaches you something you can't get from a toy dataset.

Python Libraries Required

We need three libraries: pandas for data manipulation, numpy for numerical operations, and scikit-learn for cosine similarity.

terminal
$ pip install pandas numpy scikit-learn

Building the Recommendation System

We'll walk through six steps, from importing libraries to generating live recommendations.

01

Import Required Libraries

These three imports give us everything we need for data handling and similarity calculation.

step_01_imports.py
import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity

# pandas  → data manipulation & pivot tables
# numpy   → numerical operations on arrays
# cosine_similarity → measure user taste overlap
02

Load the Dataset

Read the MovieLens CSV and inspect its structure. Each row is a single rating event: one user, one movie, one score.

step_02_load.py
ratings = pd.read_csv("ratings.csv")

print(ratings.head())
print(ratings.shape)    # (100836, 4)

# Expected columns:
# userId | movieId | rating | timestamp
output — ratings.head()
userId movieId rating timestamp
114.0964982703
134.0964981247
164.0964982224
1475.0964983815
1505.0964982931
03

Create the User–Item Matrix

Pivot the flat ratings table into a 2-D matrix where rows are users and columns are movies. Most cells will be NaN — that's the data sparsity you'll encounter in the real world.

step_03_matrix.py
user_movie_matrix = ratings.pivot_table(
    index   = 'userId',
    columns = 'movieId',
    values  = 'rating'
)

# shape: (610 users × 9724 movies)
# ~98 % of cells will be NaN (unwatched)
print(user_movie_matrix.shape)
04

Calculate User Similarity (Cosine)

Cosine similarity measures the angle between two rating vectors. A score of 1.0 = identical taste, 0.0 = no overlap. We fill NaN with 0 (unrated = neutral) before computing.

step_04_similarity.py
user_matrix_filled = user_movie_matrix.fillna(0)

similarity = cosine_similarity(user_matrix_filled)

similarity_df = pd.DataFrame(
    similarity,
    index   = user_movie_matrix.index,
    columns = user_movie_matrix.index
)

# Each cell = cosine similarity between user_i and user_j
# Diagonal is always 1.0 (user compared to themselves)
// INSIGHT
When I first implemented cosine similarity, I was surprised by how effective this simple technique can be. With just a few lines of code, we can measure how closely users' tastes align — no fancy deep learning required.
05

Build the Recommendation Function

The function finds the top-5 most similar users, averages their ratings across all movies, then returns the top 10 by predicted score — excluding movies the target user has already rated.

step_05_recommend.py
def recommend_movies(user_id):
    # 1. Find the 5 most similar users (skip index 0 = self)
    similar_users = (
        similarity_df[user_id]
        .sort_values(ascending=False)[1:6]
    )

    # 2. Pull their ratings from the matrix
    similar_users_ratings = (
        user_movie_matrix
        .loc[similar_users.index]
    )

    # 3. Average scores → top 10 movies
    recommendation_scores = similar_users_ratings.mean()

    return (
        recommendation_scores
        .sort_values(ascending=False)
        .head(10)
    )
06

Generate Movie Recommendations

Call the function for any user ID in the dataset. The output is a ranked list of movie IDs with their predicted average scores.

step_06_run.py
recommendations = recommend_movies(user_id=1)
print(recommendations)
output — top 10 recommendations for user 1
#1movieId 3184.87
#2movieId 8584.79
#3movieId 5274.74
#4movieId 12214.72
#5movieId 504.68
#6movieId 9124.65
#7movieId 9044.62
#8movieId 20194.60
#9movieId 9224.57
#10movieId 12524.55
// AUTHOR NOTE
When I first ran this function, the results were surprisingly reasonable. Even with a simple collaborative filtering approach, the system identified movies that similar users genuinely enjoyed — demonstrating how powerful basic recommendation techniques can be.

Challenges in Recommendation Systems

Despite their effectiveness, recommendation systems face several well-known challenges in production:

⚠ Cold Start Problem

New users or new items lack historical data, making it hard to produce useful recommendations until enough interactions accumulate.

⚠ Data Sparsity

Most users rate only a tiny fraction of available items, resulting in very sparse matrices that increase noise in similarity scores.

⚠ Scalability

Computing pairwise similarity across millions of users and products requires efficient approximation algorithms and distributed computing.

What I Learned While Building This Project

1

Data preparation is the bottleneck. Cleaning, pivoting, and handling missing values took far more time than writing the model itself.

2

Simple algorithms surprise you. Cosine similarity with a basic mean aggregation produces results good enough to understand the domain deeply.

3

Dataset size matters enormously. The more ratings you feed the model, the sharper the similarity scores become. Don't test on toy data alone.

// projects like this are the fastest path from theory to intuition in ML.

Conclusion

Recommendation systems play a crucial role in modern digital platforms — helping users discover relevant content and improving overall experience at scale.

In this tutorial, we built a complete movie recommendation system in Python using collaborative filtering and cosine similarity on the MovieLens dataset. The full pipeline covered loading data, building the user–item matrix, calculating similarity, and generating ranked recommendations.

Although the model is relatively simple, the same core ideas underpin the advanced recommendation systems deployed by companies like Netflix and Amazon. If you are learning data science or machine learning, building projects like this is one of the best ways to understand how algorithms transform user behavior into meaningful predictions.

Khalid Hussain

Founder of Review Publically. Writes hands-on guides on data science, machine learning and AI tools, testing every model and library before recommending it.