A content-based recommender that suggests similar movies based on genres and descriptions using TF-IDF and cosine similarity.
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))
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)
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']
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.
Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.