Freedom Sale
Independence Day Special — Unlock the AI Path 70% off our most popular AI course · Limited time offer
--Days
--Hrs
--Min
--Sec
Claim Your Discount
✦ Intermediate ⏱ 60 min

🎥 Build a Movie Recommendation System with Python

🎯 What You'll Build

A content-based recommender that suggests similar movies based on genres and descriptions using TF-IDF and cosine similarity.

📋 What You'll Need

1

Load and prepare data

Combine genres and overview into a single text feature.

import pandas as pd
import ast

df = pd.read_csv('tmdb_5000_movies.csv')
df['genres_list'] = df['genres'].apply(lambda x: ' '.join([g['name'] for g in ast.literal_eval(x)]))
df['soup'] = df['genres_list'] + ' ' + df['overview'].fillna('')
print(df[['title','soup']].head(2))
2

Build the TF-IDF matrix

Vectorise the soup and compute pairwise cosine similarity.

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel

tfidf = TfidfVectorizer(stop_words='english')
matrix = tfidf.fit_transform(df['soup'])
cosine_sim = linear_kernel(matrix, matrix)
print(f"Similarity matrix shape: {cosine_sim.shape}")
Similarity matrix shape: (4803, 4803)
3

Build the recommendation function

Given a movie title, return the top 10 most similar films.

indices = pd.Series(df.index, index=df['title'])

def recommend(title, n=10):
    idx = indices[title]
    scores = list(enumerate(cosine_sim[idx]))
    scores = sorted(scores, key=lambda x: x[1], reverse=True)[1:n+1]
    return df.iloc[[i for i, _ in scores]]['title'].tolist()

print(recommend('The Dark Knight'))
['The Dark Knight Rises', 'Batman v Superman', 'Batman Begins',
 'Man of Steel', 'Iron Man', 'The Avengers', 'Captain America',
 'Thor', 'Guardians of the Galaxy', 'Ant-Man']
💡 Tip: Add collaborative filtering using user ratings with Surprise library — combining both approaches gives you a hybrid recommender.

🎉 You Did It!

You built a content-based recommender in under 30 lines of Python. The same pattern works for books, products, articles, or any item with text metadata.

Found something wrong?

Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.