Considering NaN handling in code
I'm thinking about efficiency in my coding. It might make sense to fill NaN with 0 when computing cosine similarity, treating them as zeros. Alternatively, I could center the data. For a basic implementation, filling with zero could be the way to go. I guess it’s better to compute similarity on a matrix that's filled with 0s. So, I can use rating_mat_filled = rating_mat.fillna(0).Designing an Item-Based Collaborative Filter
I'm working on designing an item-based collaborative filtering class. In the fit method, I’ll prepare the data by copying the dataframe and extracting unique user and item IDs, while creating a user-item matrix. Then, I’ll compute item similarity using cosine similarity on the filled matrix.
For predictions in the recommend method, I need to handle cold starts, possibly suggesting popular items if the user doesn’t have ratings. I'll make sure to calculate weighted scores based on the similarity and users' ratings and then return the top recommendations. Adding a small example with a synthetic dataset could also help illustrate how to use this.Considering Edge Cases in Collaborative Filtering
I'm thinking about edge cases, particularly regarding minimum overlap in user ratings. To keep only relevant contributions, I would need to compute co-occurrence counts, but that adds complexity. It might be simpler to skip the minimum overlap and trust cosine similarity. Given the verbosity level, I shouldn't overcomplicate things.
I plan to implement item-based collaborative filtering while noting how to extend it to user-based in comments. Since this is a teaching question, clarity is important, so I’ll focus on item-based to keep the code manageable.Crafting a Collaborative Filtering Script
I need to provide a complete script that includes a sample dataset and its usage. The dataset will consist of user_id, item_id, and rating, with the code using Pandas and Sklearn.
I should begin with a brief description followed by the code. I'll ensure the code block includes comments without excessive exposition, mentioning dependencies at the top. Although they didn’t ask for it, I could also include an evaluation function to compute RMSE, but I’ll probably skip that for brevity. I must be cautious of pitfalls, especially dividing by zero when sim_sums equals zero for some items.Building a Collaborative Filtering Recommender
I’m setting up a collaborative filtering recommender system. I need to handle edge cases, like cold-start users. When users lack ratings, I can fall back on global mean ratings per item using self.ratings_df.groupby('item_id')['rating'].mean().
I’ll define my class, ensuring I compute the item similarity matrix without scikit-learn by implementing cosine similarity using NumPy.
The recommend method will calculate scores and avoid division by zero carefully, while I’ll include a predict_rating method for specific recommendations. Lastly, I'll prepare a simple example dataset to demonstrate usage. It's essential to make this code educational and accessible! Here is a minimal but complete example of an item-based collaborative filtering recommender in Python.
It uses only numpy and pandas and implements cosine similarity from scratch.
"""
Item-based Collaborative Filtering Recommender
Requirements:
pip install numpy pandas
"""
import numpy as np
import pandas as pd
class ItemBasedCFRecommender:
"""
Simple item-based collaborative filtering recommender.
Assumes input ratings DataFrame has columns: ['user_id', 'item_id', 'rating'].
"""
def __init__(self):
self.user_item_matrix = None # user x item rating matrix (pandas DataFrame)
self.item_similarity = None # item x item similarity matrix (pandas DataFrame)
self.global_item_mean = None # mean rating per item (pandas Series)
self.ratings_df = None
def fit(self, ratings_df: pd.DataFrame):
"""
Build internal matrices from raw ratings.
Parameters
----------
ratings_df : pd.DataFrame
DataFrame with columns ['user_id', 'item_id', 'rating'].
"""
self.ratings_df = ratings_df.copy()
# Create a user-item matrix: rows = users, columns = items
self.user_item_matrix = ratings_df.pivot_table(
index='user_id',
columns='item_id',
values='rating'
)
# Fill missing ratings with 0 for similarity computation
ratings_filled = self.user_item_matrix.fillna(0)
# Compute item-item cosine similarity
# Matrix shape: (n_items, n_users)
item_vectors = ratings_filled.T.values.astype(float) # items x users
norms = np.linalg.norm(item_vectors, axis=1, keepdims=True) # items x 1
norms[norms == 0] = 1e-10 # avoid division by zero
sim_matrix = item_vectors.dot(item_vectors.T) / (norms * norms.T)
# Wrap in DataFrame for convenient indexing
items = self.user_item_matrix.columns
self.item_similarity = pd.DataFrame(sim_matrix, index=items, columns=items)
# Mean rating per item (for cold-start / fallback)
self.global_item_mean = ratings_df.groupby('item_id')['rating'].mean()
def predict_rating(self, user_id, item_id):
"""
Predict a single rating for (user_id, item_id).
Returns
-------
float or np.nan
"""
# Cold start: unknown item
if item_id not in self.item_similarity.index:
return np.nan
# Cold start: unknown user
if user_id not in self.user_item_matrix.index:
return float(self.global_item_mean.get(item_id, np.nan))
user_ratings = self.user_item_matrix.loc[user_id]
rated_items = user_ratings.dropna()
# If user has not rated anything, fall back to item mean
if rated_items.empty:
return float(self.global_item_mean.get(item_id, np.nan))
# Similarities between target item and items the user has rated
sims = self.item_similarity.loc[item_id, rated_items.index] # Series
# Weighted average of user's ratings, weighted by similarity
weighted_sum = np.dot(sims.values, rated_items.values)
sim_sum = np.abs(sims.values).sum()
if sim_sum == 0:
return float(self.global_item_mean.get(item_id, np.nan))
return float(weighted_sum / sim_sum)
def recommend_for_user(self, user_id, n_recommendations=5):
"""
Recommend top-N items for a given user_id.
Returns
-------
pd.Series
Index: item_id, Values: predicted score (higher is better).
"""
# Cold-start: unknown user -> recommend most popular/highest-rated items
if user_id not in self.user_item_matrix.index:
return self.global_item_mean.sort_values(ascending=False).head(n_recommendations)
user_ratings = self.user_item_matrix.loc[user_id]
rated_items = user_ratings.dropna().index
# If user has not rated anything yet
if len(rated_items) == 0:
return self.global_item_mean.sort_values(ascending=False).head(n_recommendations)
# Similarity of all items to the items the user has rated
sim_subset = self.item_similarity[rated_items] # all_items x rated_items
# User's ratings for those items
ratings_vector = user_ratings[rated_items] # length = rated_items
# Weighted sum of similarities * ratings
weighted_sum = sim_subset.dot(ratings_vector)
# Sum of absolute similarities
sim_sum = sim_subset.abs().sum(axis=1)
# Avoid division by zero
scores = weighted_sum / sim_sum.replace(0, np.nan)
# Remove items the user has already rated
scores = scores.drop(labels=rated_items)
# Drop items that could not be scored
scores = scores.dropna()
# Top-N
return scores.sort_values(ascending=False).head(n_recommendations)
# --------------------------------------------------------------------
# Example usage
# --------------------------------------------------------------------
if __name__ == "__main__":
# Example toy dataset
data = {
'user_id': [1, 1, 1, 2, 2, 3, 3, 4],
'item_id': ['A', 'B', 'C', 'A', 'D', 'B', 'D', 'C'],
'rating': [5, 3, 4, 4, 2, 2, 5, 4]
}
ratings = pd.DataFrame(data)
# Instantiate and fit the recommender
recommender = ItemBasedCFRecommender()
recommender.fit(ratings)
# Predict a specific rating
print("Predicted rating for user 2 on item C:")
print(recommender.predict_rating(user_id=2, item_id='C'))
# Get recommendations for a user
print("\nTop-3 recommendations for user 2:")
print(recommender.recommend_for_user(user_id=2, n_recommendations=3))
This script:
- Builds an item-based collaborative filtering model from user–item–rating data.
- Computes item–item cosine similarities.
- Can predict a rating for a (user, item) pair.
- Can generate top-N recommendations for a user, excluding items already rated.
You can adapt it by:
- Changing similarity (e.g., to Pearson by centering ratings).
- Implementing a user-based CF variant (compute
user_similarity on the user-item matrix instead of item_similarity on its transpose).