Examining Recommendation Systems
I'm currently focused on the problem definition, specifically the goal of creating a collaborative filtering recommendation system in Python. It's clear that the user needs this, so I'm moving on to outlining the key concepts and defining the core aspects of collaborative filtering. Next, I plan to delve into the data structures and algorithms that are relevant to this task.
Evaluating Approach Selection
I've considered various implementation methods for collaborative filtering, including memory-based approaches using cosine similarity and model-based methods utilizing SVD and ALS, as well as the potential, though perhaps excessive, use of deep learning. Now, I'm weighing the trade-offs of each approach for a Python tutorial format, considering both ease of understanding and practical application.
Formulating the Code Plan
I've sketched out the initial data structures using a Pandas DataFrame and identified the preprocessing steps, including handling missing data. My next step will be calculating the cosine similarity between items. The plan is to create a function that takes a user's watched items and the similarity matrix as input, then recommends items based on user preferences.
Constructing Code Modules
I'm now writing Python code, starting with the memory-based collaborative filtering approach. I'm focusing on the Pandas implementation and creating dummy data. Next, I'll calculate the item-item similarity using cosine similarity, then build the recommendation function. The structure is gradually becoming clearer.
Finalizing the Strategy
I've decided on the two-part structure: a simple, understandable Item-Based CF using Pandas and Scikit-Learn for clarity, and an advanced model-based approach using Surprise and SVD for practical application. I'm now drafting the Pandas-based solution, focusing on dummy data creation, matrix formation, and the cosine similarity calculation to make the logic evident. The subsequent part will be the Surprise implementation.
Outlining Implementation Approaches
I'm now detailing the implementation plans. I have decided to provide a clear and concise approach. I'll split the tutorial in two: one using Pandas and Scikit-learn for memory-based item-based collaborative filtering, and another using the Surprise library for a model-based SVD approach, which handles the sparsity issue much better. This way, the user sees both clarity and practical application.
Here is a comprehensive guide and Python code to implement a Recommendation System.
I will provide two approaches:
- Memory-Based (Item-Item Filtering): Using
pandas and scikit-learn. This is best for understanding the math and logic.
- Model-Based (Matrix Factorization): Using the
scikit-surprise library. This is the industry standard for handling larger, sparse datasets.
Prerequisites
You will need to install the following libraries:
pip install pandas scikit-learn scikit-surprise
Approach 1: Memory-Based (Item-Item Collaborative Filtering)
In this approach, we look at the similarity between items based on user ratings. If a user liked "Movie A", and "Movie A" is mathematically similar to "Movie B" (because other users rated them similarly), we recommend "Movie B".
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
# 1. Create a dummy dataset
data = {
'User': ['Alice', 'Alice', 'Alice', 'Bob', 'Bob', 'Charlie', 'Charlie', 'Charlie', 'David', 'David'],
'Movie': ['Matrix', 'Star Wars', 'Inception', 'Matrix', 'Star Wars', 'Star Wars', 'Titanic', 'Inception', 'Titanic', 'Inception'],
'Rating': [5, 5, 4, 5, 4, 4, 5, 3, 5, 4]
}
df = pd.DataFrame(data)
print("--- Original Data ---")
print(df.head())
# 2. Create the User-Item Matrix
# Rows = Users, Columns = Movies, Values = Ratings
user_item_matrix = df.pivot_table(index='User', columns='Movie', values='Rating')
# Fill NaN with 0 (implies no rating/interaction)
user_item_matrix = user_item_matrix.fillna(0)
print("\n--- User-Item Matrix ---")
print(user_item_matrix)
# 3. Calculate Cosine Similarity between Items
# We take the transpose (.T) because we want similarity between Movies (columns), not Users
item_item_sim_matrix = cosine_similarity(user_item_matrix.T)
item_item_sim_df = pd.DataFrame(item_item_sim_matrix, index=user_item_matrix.columns, columns=user_item_matrix.columns)
print("\n--- Item Similarity Matrix ---")
print(item_item_sim_df)
# 4. Function to get recommendations
def get_recommendations(movie_name, similarity_matrix, top_n=2):
# Get similarity scores for the specific movie
sim_scores = similarity_matrix[movie_name]
# Sort the scores in descending order (most similar first)
# We drop the first one because it is the movie itself (score of 1.0)
recommended_movies = sim_scores.sort_values(ascending=False).drop(movie_name).head(top_n)
return recommended_movies
# 5. Test the system
test_movie = 'Matrix'
recommendations = get_recommendations(test_movie, item_item_sim_df)
print(f"\n--- Recommendations for '{test_movie}' ---")
print(recommendations)
Approach 2: Model-Based (SVD with Scikit-Surprise)
Memory-based approaches get slow when you have millions of users. Model-based approaches use Matrix Factorization (SVD) to predict missing ratings in the matrix. We use the surprise library, which is built specifically for this.
from surprise import Dataset, Reader, SVD
from surprise.model_selection import train_test_split
from surprise import accuracy
import pandas as pd
# 1. Setup Data
data_dict = {
'itemID': [1, 1, 1, 2, 2, 3, 3, 3, 4, 4], # Movie IDs
'userID': [9, 32, 2, 45, 9, 45, 9, 32, 2, 67], # User IDs
'rating': [3, 2, 4, 5, 1, 5, 4, 2, 4, 5]
}
df = pd.DataFrame(data_dict)
# 2. Load data into Surprise format
# The Reader is needed to tell Surprise the scale of ratings (e.g., 1-5)
reader = Reader(rating_scale=(1, 5))
data = Dataset.load_from_df(df[['userID', 'itemID', 'rating']], reader)
# 3. Split data into training and testing sets
trainset, testset = train_test_split(data, test_size=0.25)
# 4. Initialize SVD (Singular Value Decomposition) algorithm
algo = SVD()
# 5. Train the algorithm
algo.fit(trainset)
# 6. Evaluate performance
predictions = algo.test(testset)
print(f"RMSE (Root Mean Squared Error): {accuracy.rmse(predictions)}")
# 7. Predict a specific rating
# Let's predict how User 9 would rate Item 4
user_id = 9
item_id = 4
# r_ui means "actual rating" (optional, useful if you know it for comparison)
prediction = algo.predict(uid=user_id, iid=item_id, r_ui=4, verbose=True)
print(f"\nPredicted rating for User {user_id} on Item {item_id}: {prediction.est:.2f}")
How to choose?
- Memory-Based (Pandas/Cosine):
- Pros: Simple to explain, data changes reflect immediately, no training time.
- Cons: Doesn't scale well (slow), struggles with "sparse" data (when users have rated very few items).
- Model-Based (Surprise/SVD):
- Pros: Scalable, handles sparse data very well, generally higher accuracy.
- Cons: "Black box" (harder to explain why a recommendation was made), requires retraining.