The user wants to create a recommendation engine using matrix factorization.
I need to provide a complete, working example of this.
Matrix Factorization (MF) is a collaborative filtering technique. It decomposes the user-item interaction matrix into two lower-rank matrices: user features and item features.
Key steps to include:
Concept Explanation: Briefly explain what MF is (Users x Items matrix → User Matrix × Item Matrix).
Tools/Libraries: Python is the standard. numpy for basic implementation, scikit-learn (though it doesn't have a dedicated MF class for recommenders like surprise or lightfm, it has NMF), or specialized libraries like Surprise or LightFM.
Decision: I should provide two approaches.
Approach 1: A "from scratch" implementation using Gradient Descent (SGD) with NumPy. This is educational and shows how it works under the hood.
Approach 2: Using a library like scikit-learn (NMF) or Surprise. scikit-learn is more common/standard for general ML, but Surprise is better for RS evaluation. Let's stick to scikit-learn's NMF for simplicity and accessibility, or maybe just write a clean custom class to make it standalone without heavy dependencies.
Re-evaluation: A custom SGD implementation is the most illustrative for "creating" one. Using a library is just calling an API. I will provide a custom NumPy implementation because it demonstrates the mechanics of matrix factorization (prediction = dot product, learning = minimizing error via gradients).
Data: I need a dummy dataset. A small 5×5 matrix of users rating items.
Code Structure:
Import NumPy.
Define the Matrix Factorization class.
fit method: Iterates through epochs, updates P (user) and Q (item) matrices using the gradient descent formula.
predict method: Reconstructs the matrix or predicts specific user-item pairs.
Demo usage: Create data, run the model, show the output (original vs. predicted).
Refining the Code:
Need to handle missing values. In MF, usually, we only calculate error on known ratings. The loss function sums over observed (u,i) pairs.
Formula:
rui≈p
Adding a Library approach: It's good practice to mention that in production, you wouldn't write this from scratch. I'll briefly mention LightFM or Surprise or implicit feedback libraries.
Plan:
Introduction: Brief theory.
Python Implementation (from scratch): Using NumPy and SGD. This is the "meat" of the answer.
Include Regularization (to prevent overfitting).
Include Bias terms? Maybe keep it simple first. Just P and Q. If I add biases (bu,b), it becomes more accurate but complex. Let's stick to for the simplest explanation, or maybe just global mean + biases if I want it to actually work well on a tiny sample. Let's stick to basic for clarity.
Let's write the code mentally first.
python
class MF:
def __init__(self, R, k, alpha, beta, iterations):
self.R = R
self.num_users, self.num_items = R.shape
self.k = k
self.alpha = alpha
self.beta = beta
self.iterations = iterations
def train(self):
# Init P and Q with random values
self.P = np.random.rand(self.num_users, self.k)
self.Q = np.random.rand(self.num_items, self.k) # or (k, items) for dot product ease
# SGD
for i in range(self.iterations):
for u in range(self.num_users):
for i in range(self.num_items):
if self.R[u][i] > 0: # Only train on known ratings
e = self.R[u][i] - np.dot(self.P[u,:], self.Q[i,:].T)
# Update
Correction: Using nested loops in Python is slow. Vectorized approach is better, but for a "how to create" example, the loops make the math logic transparent. I will stick to loops for educational value but warn about performance.
Actually, scikit-learn's NMF is non-negative matrix factorization. Standard MF (like SVD or Funk SVD used in Netflix prize) allows negative numbers in latent factors. I should explicitly label the code as "Funk SVD" style (Gradient Descent).
Let's structure the response clearly.
Concept: Dot product of User Matrix and Item Matrix.
The Code: A robust Python class.
The Data: A sparse matrix (0s for unknown).
The Result: Predictions for the unknowns.
I will also add a small section on how to extract the "Top N" recommendations from the resulting full matrix.
Double check the math:
Error eui=rui−
Update
Update
Looks correct.
I will write the solution now.
Here is a complete guide to building a Recommendation Engine using Matrix Factorization (specifically the Funk SVD approach used in the Netflix Prize).
We will implement this from scratch using Python and NumPy to show exactly how the mathematics works, and then use it to generate recommendations.
1. The Concept
Matrix Factorization works by decomposing a large, sparse matrix of User-Item ratings into two smaller, dense matrices:
User Matrix (P): Represents the relationship between Users and latent features (hidden characteristics like "genre preference" or "price sensitivity").
Item Matrix (Q): Represents the relationship between Items and those same latent features.
If we multiply P by QT, we reconstruct the original rating matrix, but with the empty spots filled in (predicted).
2. The Implementation (From Scratch)
We will use Stochastic Gradient Descent (SGD). The algorithm loops through every known rating, calculates the error, and tweak the "latent features" to minimize that error.
python
3. Running the Engine
Let's create a dummy dataset representing 4 users and 5 movies.
python
# 1. Create Data
# Rows: Users (0-3), Cols: Movies (0-4)
# 0 means the user hasn't rated it yet.
R = np.array([
[5, 3, 0, 1, 0], # User 0
[4, 0, 0, 1, 0], # User 1
[1, 1, 0, 5, 4], # User 2
[0, 0, 5, 4, 0], # User 3
[0, 1, 5, 4, 0] # User 4
])
print("Original Matrix (0 = Unknown):\n", R)
# 2. Initialize and Train Model
# We use 3 latent factors (e.g., Action, Romance, SciFi)
mf = MatrixFactorization(n_factors=3, learning_rate=0.01, n_epochs=100)
mf.fit(R)
# 3. View Results
full_predictions = mf.predict_full_matrix()
print("\nPredicted Full Matrix (rounded):\n", np.round(full_predictions, 2))
# 4. Generate Recommendations for User 0
user_id = 0
rec_indices, rec_scores = mf.recommend(user_id, R, n_recommendations=2)
print(f"\nTop Recommendations for User {user_id}:")
for idx, score in zip(rec_indices, rec_scores):
print(f"Movie Index: {idx} (Predicted Rating: {score:.2f})")
4. How to Interpret the Output
Original Matrix: Notice User 0 has not rated Movie 2 (index 2) or Movie 4 (index 4).
Predicted Matrix: After training, the 0s are replaced with numbers.
If User 0 likes Action movies (based on their 5 and 3 ratings), and Movie 2 is an Action movie, the model will predict a high rating (e.g., 4.5) for Movie 2.
Recommendation: The recommend function looks at the predicted row for User 0, ignores the movies they have already seen, and returns the movie with the highest predicted score.
Key Concepts Summary
Latent Factors: We set n_factors=3. The math tries to figure out 3 hidden properties that define all movies and all user tastes.
Regularization: This is crucial. Without it, the model might predict a rating of 1000 for a movie just to minimize error, resulting in a model that doesn't work on new data.
Learning Rate: Controls how fast the model learns. Too fast, and it misses the best solution; too slow, and it takes forever.
Production Note
For a real-world application with millions of users, writing your own loops in Python is too slow. You would use optimized libraries such as:
Implicit: Fast Python library for collaborative filtering.
LightFM: A hybrid recommendation library.
Surprise (SciKit-Learn style): Good for prototyping standard algorithms.
u
⋅
qiT
eui=rui−pu⋅qiT
pu←pu+α⋅(2⋅eui⋅qi−λ⋅pu)
qi←qi+α⋅(2⋅eui⋅pu−λ⋅qi)
i
,
μ
P⋅QT
P⋅QT
Example Usage: Show it filling in the blanks of a sparse matrix.
Next Steps/Production: Mention libraries.
r
^
ui
∂P∂(e2)=−2(r−r^)⋅Q=−2e⋅Q
P=P+α(2e⋅Q−βP)
Q=Q+α(2e⋅P−βQ)
import numpy as np
class MatrixFactorization:
def __init__(self, n_factors=10, learning_rate=0.01, regularization=0.02, n_epochs=50):
self.n_factors = n_factors # Number of latent features
self.lr = learning_rate # Step size for gradient descent
self.reg = regularization # Penalty to prevent overfitting
self.n_epochs = n_epochs # How many times to iterate
def fit(self, R):
"""
R: User-Item rating matrix (numpy array).
0 indicates an unrated item.
"""
self.R = R
self.n_users, self.n_items = R.shape
# Initialize P (User) and Q (Item) matrices with small random values
# We cannot use zeros because the dot product would never change.
self.P = np.random.normal(scale=1./self.n_factors, size=(self.n_users, self.n_factors))
self.Q = np.random.normal(scale=1./self.n_factors, size=(self.n_items, self.n_factors))
# Training process
for epoch in range(self.n_epochs):
# Iterate through all non-zero ratings in the matrix
for u in range(self.n_users):
for i in range(self.n_items):
if self.R[u, i] > 0:
# 1. Calculate Error (Actual - Predicted)
prediction = np.dot(self.P[u, :], self.Q[i, :].T)
e_ui = self.R[u, i] - prediction
# 2. Update P and Q using Gradient Descent formulas
# We update based on the error and the regularization term
self.P[u, :] += self.lr * (2 * e_ui * self.Q[i, :] - self.reg * self.P[u, :])
self.Q[i, :] += self.lr * (2 * e_ui * self.P[u, :] - self.reg * self.Q[i, :])
# Optional: Calculate Total Error to track convergence
error = 0
for u in range(self.n_users):
for i in range(self.n_items):
if self.R[u, i] > 0:
error += pow(self.R[u, i] - np.dot(self.P[u, :], self.Q[i, :].T), 2)
# Add regularization cost
error += (self.reg/2) * (np.sum(np.square(self.P[u, :])) + np.sum(np.square(self.Q[i, :])))
if (epoch + 1) % 10 == 0:
print(f"Epoch {epoch+1}/{self.n_epochs}; Error = {error:.4f}")
def predict_full_matrix(self):
"""Returns the full matrix with predicted ratings filled in."""
return np.dot(self.P, self.Q.T)
def recommend(self, user_idx, original_R, n_recommendations=2):
"""
Generate top N recommendations for a specific user.
user_idx: The row index of the user.
original_R: The original sparse matrix (to filter out items already rated).
"""
# Predict ratings for all items for this user
predictions = np.dot(self.P[user_idx, :], self.Q.T)
# Get indices of items the user has already rated
rated_indices = np.where(original_R[user_idx, :] != 0)[0]
# Set already rated items to -infinity so they aren't recommended
predictions[rated_indices] = -np.inf
# Get top N item indices
top_indices = predictions.argsort()[-n_recommendations:][::-1]
return top_indices, predictions[top_indices]