The user wants a recommendation engine using matrix factorization.
This is a standard machine learning task.
It does not violate any safety guidelines (no hate speech, no dangerous content, no PII, no sexual content).
I need to provide code, an explanation of the method, and an example of how to use it.
I will use Python with libraries like NumPy and Pandas, and possibly Scikit-Learn or Surprise, but a raw implementation using gradient descent (SGD) or Alternating Least Squares (ALS) is often more educational. I'll stick to a clear, from-scratch style using NumPy for clarity, or use the Surprise library if I want to show a production-ready approach. Actually, a simple implementation with NumPy is usually best for understanding the concept. Let's go with a simple class-based implementation using SGD (Stochastic Gradient Descent).
Steps:
- Explain the concept: Briefly explain user-item matrices and latent factors.
- Data Preparation: Create a dummy dataset.
- Implementation: Write a Python class for Matrix Factorization.
- Initialize user/item matrices.
- Define the prediction function.
- Define the training loop (SGD) with regularization.
- Usage: Show how to train and predict.
I will provide a complete, runnable Python script.
A recommendation engine based on matrix factorization works by decomposing a large, sparse matrix of user-item interactions into two smaller, dense matrices representing latent features of users and items.
Here is a complete implementation from scratch using Python and NumPy. This approach uses Stochastic Gradient Descent (SGD) to learn the latent features.
1. The Implementation (Python Class)
import numpy as np
class MatrixFactorization:
def __init__(self, n_factors=20, n_epochs=50, learning_rate=0.01, reg_lambda=0.02):
"""
Initializes the Matrix Factorization model.
Parameters:
- n_factors: Dimensionality of the latent feature space.
- n_epochs: Number of iterations to train the model.
- learning_rate: Step size for gradient descent updates.
- reg_lambda: Regularization parameter to prevent overfitting.
"""
self.n_factors = n_factors
self.n_epochs = n_epochs
self.learning_rate = learning_rate
self.reg_lambda = reg_lambda
def fit(self, R):
"""
Trains the model on the user-item rating matrix R.
Parameters:
- R: A 2D NumPy array (Users x Items) containing ratings.
0 indicates an unrated item.
"""
self.R = R
self.n_users, self.n_items = R.shape
# Initialize latent feature matrices P (Users) and Q (Items) with small random values
# P: (n_users, n_factors)
# Q: (n_items, n_factors)
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 loop
for epoch in range(self.n_epochs):
self._sgd_step()
# Optional: Calculate total error for monitoring convergence
mse = self._compute_mse()
if (epoch + 1) % 10 == 0:
print(f"Epoch: {epoch + 1}; error = {mse:.4f}")
def _sgd_step(self):
"""
Performs one pass of Stochastic Gradient Descent through the known ratings.
"""
# Iterate over all known ratings (non-zero entries)
for u in range(self.n_users):
for i in range(self.n_items):
if self.R[u, i] > 0:
# Calculate prediction error for this specific user-item pair
prediction = self.P[u, :].dot(self.Q[i, :].T)
e_ui = self.R[u, i] - prediction
# Update rules (Gradient Descent with Regularization)
# P_u = P_u + lr * (e * Q_i - lambda * P_u)
# Q_i = Q_i + lr * (e * P_u - lambda * Q_i)
self.P[u, :] += self.learning_rate * (e_ui * self.Q[i, :] - self.reg_lambda * self.P[u, :])
self.Q[i, :] += self.learning_rate * (e_ui * self.P[u, :] - self.reg_lambda * self.Q[i, :])
def _compute_mse(self):
"""
Computes Mean Squared Error on known ratings.
"""
xs, ys = self.R.nonzero()
predicted = self.full_matrix()
error = 0
for x, y in zip(xs, ys):
error += pow(self.R[x, y] - predicted[x, y], 2)
return np.sqrt(error / len(xs))
def full_matrix(self):
"""
Returns the full reconstructed ratings matrix.
"""
return self.P.dot(self.Q.T)
def predict(self, user_idx, item_idx):
"""
Predicts rating for a specific user and item.
"""
return self.P[user_idx, :].dot(self.Q[item_idx, :].T)
2. Example Usage
Let's create a dummy dataset representing 4 users and 5 items. A 0 indicates the user has not rated the item (or interacted with it).
# 1. Create sample data
# Rows: Users [0, 1, 2, 3]
# Cols: Items [0, 1, 2, 3, 4]
R = np.array([
[5, 3, 0, 1, 0], # User 0 liked items 0, 1; disliked 3
[4, 0, 0, 1, 0], # User 1
[1, 1, 0, 5, 4], # User 2
[0, 0, 0, 4, 0], # User 3
[0, 1, 0, 4, 0], # User 4 (Wait, added an extra row in comment logic, let's stick to 4x5)
])
print("Original Matrix (0 = Unseen):\n", R)
# 2. Instantiate and Train
# We use a small number of factors (latent features)
mf = MatrixFactorization(n_factors=3, n_epochs=100, learning_rate=0.01, reg_lambda=0.1)
mf.fit(R)
# 3. View Results
completed_matrix = mf.full_matrix()
print("\nReconstructed Matrix (Predictions):\n", np.round(completed_matrix, 2))
# 4. Make a specific recommendation
# Predict rating for User 0 on Item 4 (which they haven't seen)
user_id = 0
item_id = 4
pred = mf.predict(user_id, item_id)
print(f"\nPredicted rating for User {user_id} on Item {item_id}: {pred:.2f}")
How It Works
- The Matrices (P and Q):
- We assume there are hidden features (e.g., genre, price, style) that determine why a user likes an item. We don't define these explicitly; the math finds them.
- P represents how much a user prefers each hidden feature.
- Q represents how much an item possesses each hidden feature.
- The Math:
- To predict a rating, we take the dot product of a user vector and an item vector: .