Building a recommendation system
The user is asking for a Python program that creates a recommendation system using collaborative filtering. They want it to be concise but complete, perhaps using a MovieLens-like dataset. It seems I might want to discuss user-based versus item-based collaborative filtering and possibly matrix factorization. Since they didn't provide specific data, I could create a dummy dataset with pandas. I’ll plan to include steps like importing packages, loading ratings, computing similarity, and recommending items.Designing the recommendation code
I need to mention the different variants of collaborative filtering, like user-based, item-based, and model-based methods, but I might focus on user-based for simplicity. A complete script is important, so I’ll structure it to be runnable, with comments for clarity. I’ll provide a sample CSV structure for ratings and use pandas to load the data. After creating the user-item matrix, I'll compute cosine similarity. I’ll include a prediction formula for user-based collaborative filtering. The emphasis should be on keeping the explanation minimal yet functional.Implementing the prediction function
I need to create a function, predict_ratings, that will take in a user ID, the user-item matrix, and user similarity data. It will identify unrated items and use ratings from similar users to predict ratings for those items. The function will calculate weighted averages based on similarity scores.
After implementing this, I'll create another function, recommend_items, to return the top N recommendations. I should also include comments about installing scikit-learn and provide a small sample dataset to help users run the script smoothly.Setting up the demonstration
I think it's essential to provide both options for the user: either loading a dataset from a file or using an inline example dataset for demonstration. Since the user didn't specify a dataset, I'll hardcode a small example so they can see it work. I also plan to create a function called load_ratings(path) for loading data from a file while commenting on how to adapt it for real data.
It's important to keep the code manageable and well-structured, especially under if __name__ == "__main__": for demonstration purposes. I'll focus on user-based collaborative filtering, but I'll mention item-based CF as an alternative.Planning the final code
I’ll create a final message that includes a brief introduction, the complete code with comments, and a short explanation of how to use it. I'll stick to the instructions and avoid adding unnecessary fluff. The code involves importing relevant libraries, defining functions to build user-item matrices, calculate similarities, predict ratings, and recommend items.
I’ll also include a small sample dataset inline and explain how users can replace it with their own. Lastly, I’ll remind users to install pandas and scikit-learn. Here is a complete, minimal Python program that builds a user-based collaborative filtering recommendation system.
It:
- Takes a user–item–rating table
- Builds a user–item matrix
- Computes user–user similarity (cosine)
- Predicts ratings for unseen items
- Returns top‑N recommendations for a given user
"""
Simple user-based collaborative filtering recommender in Python.
Requirements:
pip install pandas scikit-learn
"""
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
def build_user_item_matrix(ratings: pd.DataFrame) -> pd.DataFrame:
"""
Convert a long ratings table into a user-item matrix.
ratings columns: ['user_id', 'item_id', 'rating']
"""
user_item = ratings.pivot_table(
index="user_id",
columns="item_id",
values="rating"
)
return user_item
def compute_user_similarity(user_item: pd.DataFrame) -> pd.DataFrame:
"""
Compute user-user cosine similarity on the user-item matrix.
Missing ratings are filled with 0 for similarity computation.
"""
filled = user_item.fillna(0)
sim = cosine_similarity(filled)
user_ids = user_item.index
sim_df = pd.DataFrame(sim, index=user_ids, columns=user_ids)
return sim_df
def predict_user_ratings(
user_id,
user_item: pd.DataFrame,
user_sim: pd.DataFrame
) -> pd.Series:
"""
Predict ratings for all items the user has not rated yet.
Prediction formula (user-based CF):
r_hat(u, i) = sum_v sim(u, v) * r(v, i) / sum_v |sim(u, v)|
over users v who rated item i.
"""
if user_id not in user_item.index:
raise ValueError(f"Unknown user_id: {user_id}")
user_ratings = user_item.loc[user_id]
# Items that this user has not rated yet
unrated_items = user_ratings[user_ratings.isna()].index
predictions = {}
for item in unrated_items:
# Ratings of this item by all other users
item_ratings = user_item[item]
# Users who rated this item
mask = ~item_ratings.isna()
if mask.sum() == 0:
# No information about this item
continue
# Similarities between target user and users who rated this item
sims = user_sim.loc[user_id, mask]
ratings = item_ratings[mask]
numerator = (sims * ratings).sum()
denominator = sims.abs().sum()
if denominator == 0:
continue
predictions[item] = numerator / denominator
# Return predicted ratings sorted descending
return pd.Series(predictions).sort_values(ascending=False)
def recommend_items(
user_id,
user_item: pd.DataFrame,
user_sim: pd.DataFrame,
n: int = 5
) -> pd.Series:
"""
Recommend top-n items for a given user based on predicted ratings.
"""
preds = predict_user_ratings(user_id, user_item, user_sim)
return preds.head(n)
def main():
# -----------------------------------------------------------------
# Example data (you can replace this with your own ratings file)
# -----------------------------------------------------------------
# Each row: a user rated an item with a score (1–5)
data = [
{"user_id": 1, "item_id": "A", "rating": 4},
{"user_id": 1, "item_id": "B", "rating": 5},
{"user_id": 1, "item_id": "D", "rating": 2},
{"user_id": 2, "item_id": "A", "rating": 5},
{"user_id": 2, "item_id": "C", "rating": 3},
{"user_id": 3, "item_id": "B", "rating": 4},
{"user_id": 3, "item_id": "C", "rating": 2},
{"user_id": 3, "item_id": "D", "rating": 5},
{"user_id": 4, "item_id": "A", "rating": 3},
{"user_id": 4, "item_id": "B", "rating": 3},
{"user_id": 4, "item_id": "C", "rating": 4},
]
ratings = pd.DataFrame(data)
# If you have a CSV file instead, use:
# ratings = pd.read_csv("ratings.csv") # expects user_id,item_id,rating
# -----------------------------------------------------------------
# Build the recommender
# -----------------------------------------------------------------
user_item = build_user_item_matrix(ratings)
user_sim = compute_user_similarity(user_item)
# -----------------------------------------------------------------
# Get recommendations for a user
# -----------------------------------------------------------------
target_user = 1
top_n = 3
recs = recommend_items(target_user, user_item, user_sim, n=top_n)
print(f"Top {top_n} recommendations for user {target_user}:")
# recs is a Series: index = item_id, value = predicted rating
print(recs)
if __name__ == "__main__":
main()
To adapt this to your data:
- Put your ratings in a CSV with columns:
user_id,item_id,rating.
- Replace the example
data and ratings = pd.DataFrame(data) with:
ratings = pd.read_csv("path_to_your_ratings.csv")
- Run the script and call
recommend_items(your_user_id, user_item, user_sim, n=K) to get top‑K recommendations.
If you want an item-based version or a matrix-factorization approach (e.g., SVD), say so and I’ll extend this.