How To Build A Movie Recommendation System In Python (Step-by-Step)
// outline
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
Types of Recommendation Systems
There are three main approaches used in modern recommendation systems:
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
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
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.
Python Libraries Required
We need three libraries: pandas for data manipulation, numpy for numerical operations, and scikit-learn for cosine similarity.
$ pip install pandas numpy scikit-learn
Building the Recommendation System
We'll walk through six steps, from importing libraries to generating live recommendations.
Import Required Libraries
These three imports give us everything we need for data handling and similarity calculation.
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
Load the Dataset
Read the MovieLens CSV and inspect its structure. Each row is a single rating event: one user, one movie, one score.
ratings = pd.read_csv("ratings.csv")
print(ratings.head())
print(ratings.shape) # (100836, 4)
# Expected columns:
# userId | movieId | rating | timestamp
| userId | movieId | rating | timestamp |
|---|---|---|---|
| 1 | 1 | 4.0 | 964982703 |
| 1 | 3 | 4.0 | 964981247 |
| 1 | 6 | 4.0 | 964982224 |
| 1 | 47 | 5.0 | 964983815 |
| 1 | 50 | 5.0 | 964982931 |
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.
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)
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.
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)
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.
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)
)
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.
recommendations = recommend_movies(user_id=1)
print(recommendations)
Challenges in Recommendation Systems
Despite their effectiveness, recommendation systems face several well-known challenges in production:
New users or new items lack historical data, making it hard to produce useful recommendations until enough interactions accumulate.
Most users rate only a tiny fraction of available items, resulting in very sparse matrices that increase noise in similarity scores.
Computing pairwise similarity across millions of users and products requires efficient approximation algorithms and distributed computing.
What I Learned While Building This Project
Data preparation is the bottleneck. Cleaning, pivoting, and handling missing values took far more time than writing the model itself.
Simple algorithms surprise you. Cosine similarity with a basic mean aggregation produces results good enough to understand the domain deeply.
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.
// related reads