0
0
ML Pythonml~5 mins

Collaborative filtering in ML Python

Choose your learning style9 modes available
Introduction

Collaborative filtering helps recommend things by looking at what others liked. It finds patterns in user choices to suggest new items you might enjoy.

When you want to suggest movies to a user based on what similar users liked.
When an online store wants to recommend products based on other customers' purchases.
When a music app suggests songs by comparing your listening habits with others.
When a news website recommends articles based on what readers with similar interests read.
When a social platform suggests friends or groups by analyzing connections of similar users.
Syntax
ML Python
from sklearn.neighbors import NearestNeighbors

model = NearestNeighbors(n_neighbors=3, metric='cosine')
model.fit(user_item_matrix)

# To find similar users or items:
distances, indices = model.kneighbors(target_vector.reshape(1, -1))

user_item_matrix is a table where rows are users and columns are items, filled with ratings or interactions.

The metric='cosine' measures similarity between users or items.

Examples
Set up a model to find 2 nearest neighbors using cosine similarity.
ML Python
from sklearn.neighbors import NearestNeighbors

model = NearestNeighbors(n_neighbors=2, metric='cosine')
model.fit(user_item_matrix)
Find neighbors similar to the first user in the matrix.
ML Python
distances, indices = model.kneighbors(user_item_matrix[0].reshape(1, -1))
Sample Model

This program finds the two users most similar to user 0 based on their item ratings using cosine similarity.

ML Python
import numpy as np
from sklearn.neighbors import NearestNeighbors

# Sample user-item ratings matrix (rows: users, columns: items)
user_item_matrix = np.array([
    [5, 3, 0, 1],
    [4, 0, 0, 1],
    [1, 1, 0, 5],
    [0, 0, 5, 4],
    [0, 1, 5, 4],
])

# Create and train the model
model = NearestNeighbors(n_neighbors=2, metric='cosine')
model.fit(user_item_matrix)

# Find 2 users most similar to user 0
distances, indices = model.kneighbors(user_item_matrix[0].reshape(1, -1))

print("User 0's nearest neighbors:")
for i, (dist, idx) in enumerate(zip(distances[0], indices[0])):
    print(f"Neighbor {i+1}: User {idx} with distance {dist:.3f}")
OutputSuccess
Important Notes

Collaborative filtering can be user-based or item-based depending on whether you compare users or items.

Cosine similarity is common because it measures how similar two users' preferences are regardless of rating scale.

Cold start problem happens when new users or items have no data, making recommendations hard.

Summary

Collaborative filtering recommends items by finding similar users or items.

It uses a matrix of user-item interactions and similarity measures like cosine distance.

This method is popular in recommendation systems for movies, products, music, and more.