AI & Machine Learning Master Course — 153. Collaborative filtering and matrix factorization
Smartyfy AI & Machine Learning Master Course
Course ID: smartyfy-ai-ml-master-200
Lesson 153: Collaborative filtering and matrix factorization
Prerequisites: Lesson 152. Learning outcome: Learn user-item representations and explain sparse interaction modeling.
From shared behavior to latent vectors
Collaborative filtering learns from patterns across users and items. It can connect two items without shared text or categories when their interaction patterns support that connection. Matrix factorization expresses this idea with a short vector for each user and each item. The vectors are learned parameters, not demographic descriptions or a record of why someone acted.
For an explicit rating, our prediction is a fixed training mean plus a dot product: prediction(u,i) = mu + P[u] dot Q[i]. With four users, four items, and two latent coordinates, P and Q each have shape (4,2). Their product has shape (4,4). Each prediction combines shared user and item vectors.
The residual matrix P times Q-transpose has rank at most two. Adding the constant mean changes the complete prediction matrix, so the rank bound applies specifically to the factor product. Latent coordinates can rotate together without changing dot products; human-trait interpretations require evidence.
Define the observed training objective
The lab uses fictional explicit ratings from one to five. A zero in the storage array means unobserved, not a genuine zero-star rating. We first identify observed cells, then remove four of those cells from the training mask. Missing cells and held-out ratings contribute no rating-error term to optimization.
Let N be the number of training ratings. Our loss is half the mean squared error on those N cells, plus lambda/2 times the sum of squared values in P and Q. Here lambda is 0.02. The penalty discourages large factors; it does not prove good generalization. A user or item with no training feedback needs a separate cold-start strategy because its interaction-specific representation lacks evidence.
Write E as the prediction error on training cells and zero everywhere else. The gradients are E times Q divided by N, plus lambda P; and E-transpose times P divided by N, plus lambda Q. Calculate both gradients from the same parameter state before updating either matrix. Otherwise the code implements a different update sequence.
An implicit-feedback objective needs different assumptions. A missing click is not an explicit low rating. Weighted implicit objectives or sampled pairwise preferences can use unobserved interactions as uncertain training signals, but their weights and sampling policy are modeling choices. Do not silently transplant the explicit-rating loss into that setting.
CPU lab: fit factors and keep the disappointing result
Run this complete NumPy example on CPU. It trains the two factor matrices with 3,000 full-batch gradient steps. The fixed mean, 2.75, uses only eight training ratings. Four observed ratings are reserved for evaluation; their values never enter the mean or gradients.
The printed training RMSE is approximately 0.113137, while held-out RMSE is approximately 2.157074 rating points. The held-out predictions are approximately [1.469073, 1.877705, 3.165506, 2.402599], against actual ratings [4,1,1,5]. The model fits the available training cells closely and predicts several missing observations poorly. This is an instructional failure of generalization, not a successful recommender benchmark.
The random seed makes this tiny run reproducible. It does not make the split representative. All users and items retain training observations, so the test concerns a small warm-start matrix-completion task. It does not measure future recommendation quality, new-item performance, or satisfaction. No downloaded data, pretrained model, or external service is used.
import numpy as np
rng=np.random.default_rng(153)
# Explicit fictional ratings; zeros below are unobserved placeholders, not ratings.
ratings=np.array([[5.,4.,0.,1.],[4.,0.,1.,1.],[1.,1.,5.,0.],[0.,1.,4.,5.]])
mask=ratings>0
held=[(0,1),(1,2),(2,0),(3,3)]
train=mask.copy()
for u,i in held:train[u,i]=False
mu=ratings[train].mean()
P=rng.normal(0,.1,(4,2));Q=rng.normal(0,.1,(4,2))
reg=.02
for _ in range(3000):
error=np.where(train,mu+P@Q.T-ratings,0.)
gP=error@Q/train.sum()+reg*P
gQ=error.T@P/train.sum()+reg*Q
P-=.2*gP;Q-=.2*gQ
pred=mu+P@Q.T
train_rmse=np.sqrt(np.mean((pred[train]-ratings[train])**2))
test_rmse=np.sqrt(np.mean([(pred[u,i]-ratings[u,i])**2 for u,i in held]))
print('Training / held-out ratings:',int(train.sum()),len(held))
print('Training mean:',mu)
print('Train / held-out RMSE:',round(float(train_rmse),6),round(float(test_rmse),6))
print('Held-out predictions:',[round(float(pred[u,i]),6) for u,i in held])
assert train.sum()==8 and len(held)==4
assert all(not train[u,i] for u,i in held)
assert np.isfinite(pred).all()
Read both error measurements
| Partition | Observed ratings | RMSE |
|---|---|---|
| Training | 8 | 0.113137 |
| Held out | 4 | 2.157074 |
What to improve without leaking evaluation labels
Compare a training-mean baseline, bias terms, dimensions, and regularization on separate development data. Keep final evaluation untouched. This tiny dataset cannot support stable comparisons; report that limitation rather than repeatedly tuning on the four test ratings.
RMSE measures rating prediction, whereas a recommendation list is judged by ordering eligible items. The same model can have reasonable RMSE yet poor top-of-list relevance. Evaluate the metric and candidate universe that match the intended task. Record which users and items were eligible and how repeated interactions were split.
Our dense array is convenient for teaching. At large scale, materializing every user-item prediction can be prohibitive even when the factor matrices are compact. Optimize over sparse observations and retrieve candidates without building the full score matrix. This lesson implements only the small dense training calculation.
Four practice questions with worked answers
Practice 1
Compute a prediction when mu = 3, P[u] = [1,2], and Q[i] = [0.5,-0.25].
Answer: The dot product is 1 times 0.5 plus 2 times -0.25, which equals zero. The prediction is therefore 3. The shared mean and the personalized factor contribution are separate parts of the score.
Practice 2
How many factor values are trained for four users, four items, and two dimensions?
Answer: P contains eight values and Q contains eight, for sixteen trained factor values. The fixed training mean is an additional stored scalar. This toy size provides no storage advantage over sixteen matrix entries; compactness becomes useful when the dimensions are small relative to both populations.
Practice 3
Why must a held-out rating be removed from the mask before computing mu?
Answer: The mean is part of the fitted predictor. Including the held-out value would let evaluation information influence every prediction, even if gradient updates later exclude that cell. Both initialization statistics and optimization must respect the split.
Practice 4
What can you conclude from training RMSE 0.113137 and held-out RMSE 2.157074?
Answer: The model fits its eight training observations much more closely than these four held-out observations. The gap warns against a quality claim. It does not identify one unique cause or establish how the method would behave on a representative larger dataset.
Five multiple-choice questions
Question 1
What do zeros in the lab’s rating array represent?
- A. Held-out ratings whose true value is known to be zero.
- B. Observed dislikes with the same weight as one-star ratings.
- C. Unobserved entries excluded from the explicit rating-error objective.
Correct: C. The storage convention marks missing observations. The separate masks distinguish training ratings from observed held-out ratings.
Question 2
Which statistic is used to compute the fixed mean?
- A. Every array cell, including missing-value placeholders.
- B. Only the observed training ratings.
- C. All observed ratings, including the four evaluation cells.
Correct: B. The predictor’s mean must use training information. Both held-out labels and placeholder zeros would change that intended statistic.
Question 3
What does low training RMSE establish here?
- A. Close fit to the observed training ratings under this objective.
- B. Accurate predictions for users with no training observations.
- C. Reliable ranking of all unseen items for each user.
Correct: A. Training fit is directly measured. Ranking quality and cold-start performance need their own evaluation and are not implied by that fit.
Question 4
Why calculate gP and gQ before changing P or Q?
- A. To guarantee that the jointly optimized problem is convex.
- B. To take both gradient components at the same parameter state.
- C. To allow held-out ratings to contribute only to the Q update.
Correct: B. Simultaneous gradient descent evaluates the gradient at one state. The mask still excludes held-out cells, and the factorized objective is not jointly convex.
Question 5
What is guaranteed to be preserved under every shared orthogonal rotation of both factor matrices?
- A. Their user-item dot products.
- B. Each factor coordinate’s original numerical value.
- C. A uniquely identifiable meaning for each latent coordinate.
Correct: A. The orthogonal rotation cancels in the product. Individual coordinates and their interpretations need not stay fixed.
Common pitfalls
Do not train on missing-value placeholders, compute the mean from evaluation ratings, read latent coordinates as proven human traits, or hide poor held-out performance. Avoid selecting dimensions or penalties repeatedly on the final test cells.
Summary
Matrix factorization shares information through learned user and item vectors. The observation mask defines the training problem, regularization constrains the factors, and separate evaluation reveals whether the fit transfers. This actual NumPy training run demonstrates both the mechanics and a substantial generalization gap.