Collaborative filtering helps recommend things by looking at what others liked. It finds patterns in user choices to suggest new items you might enjoy.
Collaborative filtering in 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.
from sklearn.neighbors import NearestNeighbors model = NearestNeighbors(n_neighbors=2, metric='cosine') model.fit(user_item_matrix)
distances, indices = model.kneighbors(user_item_matrix[0].reshape(1, -1))
This program finds the two users most similar to user 0 based on their item ratings using cosine similarity.
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}")
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.
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.
Practice
collaborative filtering in recommendation systems?Solution
Step 1: Understand collaborative filtering concept
Collaborative filtering finds users with similar tastes and recommends items they liked.Step 2: Compare options to definition
Only It recommends items based on similar users' preferences. matches this idea; others describe different methods or unrelated ideas.Final Answer:
It recommends items based on similar users' preferences. -> Option BQuick Check:
Collaborative filtering = similar users' preferences [OK]
- Confusing collaborative filtering with content-based filtering
- Thinking it uses item descriptions only
- Assuming it recommends randomly
u and v in Python using NumPy?Solution
Step 1: Recall cosine similarity formula
Cosine similarity = dot product of vectors divided by product of their norms.Step 2: Match formula to code
np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v)) correctly implements this formula using NumPy functions.Final Answer:
np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v)) -> Option DQuick Check:
Cosine similarity formula = np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v)) [OK]
- Adding norms instead of multiplying
- Multiplying dot product by norms
- Dividing by sum of norms
User 1: [5, 3, ?]
User 2: [4, 2, 1]
User 3: [1, 5, 4]Assume similarity weights are:
User 1 & User 2: 0.9
User 1 & User 3: 0.1
Use weighted average: (0.9*1 + 0.1*4) / (0.9 + 0.1)
Solution
Step 1: Calculate weighted sum of ratings
Weighted sum = (0.9 * 1) + (0.1 * 4) = 0.9 + 0.4 = 1.3Step 2: Calculate sum of weights and divide
Sum weights = 0.9 + 0.1 = 1.0; Predicted rating = 1.3 / 1.0 = 1.3Final Answer:
1.3 -> Option CQuick Check:
Weighted average = 1.3 [OK]
- Forgetting to divide by sum of weights
- Mixing up user similarities
- Using unweighted average
import numpy as np item1 = np.array([5, 3, 0]) item2 = np.array([4, 0, 1]) similarity = np.dot(item1, item2) / (np.linalg.norm(item1) + np.linalg.norm(item2)) print(similarity)
What is the error in this code?
Solution
Step 1: Review cosine similarity formula
Cosine similarity divides dot product by product of norms, not sum.Step 2: Identify code mistake
Code uses addition in denominator instead of multiplication, causing wrong similarity value.Final Answer:
Using addition instead of multiplication in denominator for cosine similarity. -> Option AQuick Check:
Denominator must multiply norms, not add [OK]
- Adding norms instead of multiplying
- Confusing dot and cross product
- Assuming zero values cause errors
Solution
Step 1: Understand sparsity problem in collaborative filtering
Sparse matrices have many missing values, making similarity calculations unreliable.Step 2: Identify best method to handle sparsity
Matrix factorization like SVD reduces dimensionality and predicts missing ratings effectively.Final Answer:
Use matrix factorization techniques like Singular Value Decomposition (SVD). -> Option AQuick Check:
SVD handles sparsity well [OK]
- Filling missing ratings with zeros biases similarity
- Ignoring incomplete users loses valuable data
- Random recommendations ignore user preferences
Ready to prove it?
Pass the test and this pattern moves unknown
