The user wants a Python program to create a recommendation system using collaborative filtering.
I need to provide a complete, runnable, and understandable example.
1. Understand the Goal:
- Objective: Build a recommendation system.
- Method: Collaborative Filtering.
- Language: Python.
- Libraries needed:
pandas for data manipulation, numpy for math, and scikit-learn for similarity metrics (cosine similarity).
2. Choose the Approach:
Collaborative filtering has two main types:
- User-Based: "Users like you liked these items."
- Item-Based: "Users who liked this item also liked these items."
Item-based is often more stable (items don't change personalities as much as users do), but User-based is more intuitive for a first example. I will provide a clear implementation of User-Based Collaborative Filtering using Cosine Similarity, as it's the standard "Hello World" approach for this topic.
3. Design the Code Structure:
- Data: I need a dummy dataset. Creating a dictionary of users, items, and ratings is the easiest way. I'll convert this to a Pandas DataFrame.
- Matrix: Convert the data into a User-Item matrix (rows=users, columns=items).
- Similarity: Calculate the similarity between users using Cosine Similarity.
- Prediction: Predict ratings for items a user hasn't rated yet.
- Recommendation: Sort these predictions and output the top N items.
4. Step-by-Step Implementation Plan:
- Step 1: Import Libraries.
pandas, numpy, sklearn.metrics.pairwise.
- Step 2: Create Data. A simple dictionary mimicking movie ratings.
- Step 3: Pre-processing. Pivot the data to get the matrix. Fill NaNs (usually with 0, though mean-centering is better for Cosine Similarity, sticking to 0 is simpler for a basic tutorial).
- Step 4: Calculate Similarity. Compute cosine similarity between users.
- Step 5: Define Prediction Function. This is the tricky part. I need a function that takes a user, finds similar users, and weights their ratings by similarity to predict the target user's rating.
- Simplification: Instead of writing a complex weighted average loop from scratch (which is prone to errors in a quick script), I might use a library like
surprise or keep the math simple in pandas/numpy.
- Decision: Let's stick to pure
pandas/numpy for transparency so the user sees the logic, rather than hiding it behind a "black box" library function. It's more educational.
- Step 6: Generate Recommendations. Find items the target user hasn't rated, predict ratings, and sort.
5. Refining the "Math" part:
The prediction formula for user u and item i is often:
Pu, where are neighbors.
6. Drafting the Code (Mental or scratchpad):
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
# Data
data = {'User': ['A', 'A', 'B', 'B', 'C'], 'Item': ['X', 'Y', 'X', 'Z', 'Y'], 'Rating': [5, 3, 4, 5, 2]}
df = pd.DataFrame(data)
# Matrix
matrix = df.pivot_table(index='User', columns='Item', values='Rating').fillna(0)
# Similarity
user_sim = cosine_similarity(matrix)
user_sim_df = pd.DataFrame(user_sim, index=matrix.index, columns=matrix.index)
# Predict
# This is the complex part to write concisely.
# A simple way:
# 1. Get weights (similarities) for the target user against all others.
# 2. Get ratings for the specific item from other users.
# 3. Dot product / sum of weights.
7. Adding "Item-Based" alternative:
It's good practice to mention that Item-Based exists. I will focus the main code on User-Based for simplicity, but add a comment or a small variation showing how easy it is to switch to Item-Based (just transpose the matrix).
8. Polishing the Output:
The explanation needs to cover:
- What Collaborative Filtering is.
- How Cosine Similarity works (angle between vectors).
- The difference between User-Based and Item-Based.
- Code walkthrough.
9. Final Code Structure Review:
- I will create a class-based structure? Or functional? Functional is easier for a script.
- I will use a dictionary dataset so they don't need an external CSV file.
- I will include comments explaining every line.
10. Self-Correction during drafting:
- Issue: Standard Cosine Similarity doesn't account for "mean centering" (bias). User A rates everything 5, User B rates everything 1. They have similar preferences (relative ordering), but low cosine similarity.
- Fix: Ideally, I should subtract the user mean before calculating similarity.
- Decision: To keep the code accessible to a beginner, I will stick to raw ratings but mention Mean Centering as an optimization in the explanation. Adding mean centering logic adds 3-4 lines of matrix manipulation that might confuse a beginner. I'll keep it simple first.
11. Constructing the Final Response:
- Introduction: Define Collaborative Filtering.
- Prerequisites:
pandas, scikit-learn.
- The Code: A complete script.
- Explanation: Break down the steps (Data -> Matrix -> Similarity -> Predict).
- Next Steps: Mention SVD, Matrix Factorization, or Libraries like
Surprise.
Let's write the code.
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
# 1. Create Data
data = {
'User': ['Alice', 'Alice', 'Alice', 'Bob', 'Bob', 'Charlie', 'Charlie', 'Charlie', 'David'],
'Movie': ['Titanic', 'Avatar', 'Inception', 'Titanic', 'Inception', 'Avatar', 'Inception', 'Interstellar', 'Titanic'],
'Rating': [5, 4, 5, 4, 5, 3, 4, 5, 3]
}
df = pd.DataFrame(data)
# ... pivot table logic ...
# ... similarity logic ...
# ... recommendation function ...
This looks solid. I will present this.
One specific detail to handle in the prediction logic:
When predicting, we only want to consider neighbors who have actually rated the item.
Formula: weighted_sum / sum_of_weights.
I need to make sure I don't divide by zero.
Okay, I will write a robust but simple function recommend_movies(target_user).
Refined Code Plan:
- Setup Data.
- Create Pivot Table.
- Calculate Cosine Similarity Matrix.
- Function
recommend(user):
- Check if user exists.
- Get similarity scores for this user vs all others.
- Iterate through unrated movies.
- For each unrated movie, calculate weighted score based on similar users who rated it.
- Sort and return.
This covers all bases. I'm ready to generate the response.
This guide provides a complete, runnable Python program to build a recommendation system using User-Based Collaborative Filtering.
The Concept
Collaborative Filtering works on the principle: "Show me items that users with similar tastes to mine liked."
We will use Cosine Similarity to measure how similar users are based on their ratings and recommend movies that a similar user loved but the target user hasn't seen yet.
Prerequisites
You will need pandas for data handling and scikit-learn for the mathematical calculations.
pip install pandas numpy scikit-learn
The Python Code
Save this code into a file (e.g., recommender.py) and run it.
import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
def load_data():
"""
Creates a mock dataset of users rating movies.
In a real scenario, this would come from a CSV or database.
"""
data = {
'User': ['Alice', 'Alice', 'Alice', 'Alice',
'Bob', 'Bob', 'Bob',
'Carol', 'Carol', 'Carol',
'Dave', 'Dave', 'Dave'],
'Movie': ['Titanic', 'Avatar', 'Inception', 'The Notebook',
'Titanic', 'Inception', 'Interstellar',
'The Notebook', 'Titanic', 'Avatar',
'Inception', 'Interstellar', 'The Dark Knight'],
'Rating': [5, 4, 5, 5,
4, 5, 4,
5, 4, 3,
5, 4, 5]
}
df = pd.DataFrame(data)
return df
def create_user_item_matrix(df):
"""
Pivots the data to create a matrix where:
- Index (Rows) = Users
- Columns = Items (Movies)
- Values = Ratings
"""
matrix = df.pivot_table(index='User', columns='Movie', values='Rating')
return matrix
def compute_user_similarity(matrix):
"""
Computes cosine similarity between users.
Fills NaN with 0 temporarily for calculation (implies unrated items have 0 preference).
"""
# Fill NaN with 0 for calculation
matrix_filled = matrix.fillna(0)
# Calculate cosine similarity
user_sim = cosine_similarity(matrix_filled)
# Convert back to a DataFrame for readability
user_sim_df = pd.DataFrame(user_sim, index=matrix.index, columns=matrix.index)
return user_sim_df
def recommend_movies(target_user, user_item_matrix, user_similarity_df, n_recommendations=3):
"""
Generates recommendations for a target user.
"""
# 1. Check if user exists
if target_user not in user_item_matrix.index:
print(f"User {target_user} not found.")
return []
# 2. Get similarity scores for the target user against all other users
# Sort descending so most similar users are first
sim_scores = user_similarity_df[target_user].sort_values(ascending=False)
# Remove the target user themselves from the list (similarity is always 1.0)
sim_scores = sim_scores.drop(target_user)
# 3. Identify items the target user has already rated
user_ratings = user_item_matrix.loc[target_user]
rated_items = user_ratings[user_ratings.notna()].index.tolist()
# 4. Predict ratings for unrated items
recommendations = {}
# We look at the items rated by the top N similar users
# For simplicity, let's look at the top 2 neighbors
top_neighbors = sim_scores.head(2).index
for neighbor in top_neighbors:
neighbor_weight = sim_scores[neighbor] # How similar is this neighbor?
neighbor_ratings = user_item_matrix.loc[neighbor]
# Iterate through items the neighbor rated
for movie, rating in neighbor_ratings.dropna().items():
if movie not in rated_items:
# If we haven't added this movie yet, or we found a higher score
if movie not in recommendations:
# Weighted score = Neighbor Rating * Similarity
recommendations[movie] = rating * neighbor_weight
else:
recommendations[movie] += rating * neighbor_weight
# Sort items by predicted score
sorted_recs = sorted(recommendations.items(), key=lambda x: x[1], reverse=True)
return sorted_recs[:n_recommendations]
# --- Main Execution ---
# 1. Load and Prepare Data
df = load_data()
print("--- Raw Data Sample ---")
print(df.head(), "\n")
# 2. Create Matrix
user_item_matrix = create_user_item_matrix(df)
print("--- User-Item Matrix ---")
print(user_item_matrix.fillna('-'), "\n") # Displaying as '-' for readability
# 3. Calculate Similarities
user_sim_df = compute_user_similarity(user_item_matrix)
print("--- User Similarity Matrix ---")
print(user_sim_df.round(2), "\n")
# 4. Generate Recommendations for a specific user
target_user = 'Dave'
print(f"--- Recommendations for {target_user} ---")
recs = recommend_movies(target_user, user_item_matrix, user_sim_df)
if recs:
for movie, score in recs:
print(f"Movie: {movie} (Predicted Score: {score:.2f})")
else:
print("No recommendations found (perhaps the user has seen everything or has no similar neighbors).")
How It Works
-
The Matrix (create_user_item_matrix):
We transform the list of ratings into a grid. Rows represent Users, Columns represent Movies. The intersection is the rating. NaN means the user hasn't seen/rated it.
Visualizing the Matrix:
Movie Avatar Inception Titanic ...
User
Alice 5.0 5.0 5.0 ...
Bob NaN 5.0 4.0 ...
-
Similarity (compute_user_similarity):
We use Cosine Similarity. Imagine plotting users on a graph based on their ratings. The closer they are geometrically (the smaller the angle between their vectors), the more similar they are.
- Alice and Bob both rated Titanic and Inception similarly. Their similarity score will be high (close to 1.0).
-
Prediction & Recommendation (recommend_movies):
This is the core logic.
- We pick a target user (e.g., "Dave").
- We find the user(s) most similar to Dave.
- We look at movies those "neighbors" rated highly.
- We filter out movies Dave has already seen.
- We calculate a Weighted Score: (Neighbor's Rating × Similarity Score).
- We return the top-scoring movies.
How to Improve This System
In a production environment, you would typically make the following upgrades:
- Item-Based Filtering: Instead of finding similar users, find similar items. (e.g., "Users who liked Titanic also liked Avatar"). This is often more stable because item characteristics don't change as often as user tastes.
- Matrix Factorization (SVD): Instead of just using cosine similarity, advanced systems use algorithms like Singular Value Decomposition (SVD) to "fill in the blanks" of the matrix more accurately. This is the algorithm used in the famous Netflix Prize competition.
- Cold Start Handling: The code above fails if a new user appears with no history. Real systems use Hybrid Filtering (combining Collaborative Filtering with Content-Based Filtering) to solve this.