Sub topic 10
Latent factors and matrix factorization
This chapter assumes you know the user-item matrix and its sparsity, and that you are comfortable with dot products and NumPy arrays. Neighborhood methods predict a rating by looking up similar users or items. Matrix factorization takes a different route. It learns a short vector for every user and every item, and it predicts a rating as the dot product of two vectors. This chapter covers the model and its objective. The next chapter covers how to train it.
From neighbors to latent factors
Neighborhood methods work directly on the raw rating rows or columns. They have two weaknesses on sparse data:
- Two users with no co-rated items have no defined similarity, even if their tastes are alike.
- Every prediction needs a search over many neighbors, and that search gets slower as the data grows.
A latent factor model compresses each user and each item into k numbers. A latent factor is a hidden dimension that nobody labeled in advance. The model discovers it because it helps explain the observed ratings. For movies, one dimension might line up with "serious versus light" and another with "action versus dialogue". Those names are your interpretation. The model only learns numbers.
Each user u gets a vector p_u and each item i gets a vector q_i, both of length k. The predicted rating is:
r_hat(u, i) = p_u · q_iA high score means the user's vector points in roughly the same direction as the item's vector. The two vectors live in the same space. That shared space is why a user who never rated anything similar to an item can still receive a prediction for it.
The matrix view
Stack all user vectors into a matrix P of shape n_users × k. Stack all item vectors into Q of shape n_items × k. Then the full matrix of predictions is:
R_hat = P @ Q.TR_hat is dense. It has a prediction for every pair, including pairs with no observed rating. The model is a low-rank approximation of R: the product of two thin matrices stands in for one large matrix.
Why this saves parameters
The factorization stores far fewer numbers than the full matrix, and that forces the model to generalize.
| Quantity | Formula | Example: 10,000 users, 5,000 items, k = 20 |
|---|---|---|
| Full matrix cells | n_users × n_items | 50,000,000 |
| Factor parameters | (n_users + n_items) × k | 300,000 |
With only 300,000 parameters, the model cannot memorize each rating. It has to find structure that many ratings share. A low-rank model fills in missing cells because the shared structure constrains them.
The objective: fit only the observed cells
Training chooses P and Q so that predictions match the known ratings. The key rule is that the loss counts observed entries only:
loss = sum over observed (u, i) of (r_ui - p_u · q_i)^2
+ lambda * (sum of ||p_u||^2 + sum of ||q_i||^2)The second term is L2 regularization. It penalizes large vectors, and lambda sets how strongly. Without it, a model with enough factors can match the training ratings almost exactly and then predict poorly on new ones.
The following code computes this loss for a random starting point. It uses a boolean mask so the zeros that mean "not rated" never count as errors.
import numpy as np
R = np.array([
[5, 3, 0, 1],
[4, 0, 0, 1],
[1, 1, 0, 5],
[1, 0, 0, 4],
[0, 1, 5, 4],
], dtype=float)
mask = R > 0
def regularized_loss(R, mask, P, Q, reg=0.05):
pred = P @ Q.T
sq_err = ((R - pred)[mask] ** 2).sum()
penalty = reg * ((P ** 2).sum() + (Q ** 2).sum())
return sq_err + penalty
rng = np.random.default_rng(0)
k = 2
P = rng.normal(0, 0.1, (R.shape[0], k))
Q = rng.normal(0, 0.1, (R.shape[1], k))
print(f"loss at random start: {regularized_loss(R, mask, P, Q):.2f}")
print(f"prediction for user 0, item 2: {P[0] @ Q[2]:.3f}")At a random start the predictions are close to zero, so the loss is large. Training lowers it by adjusting P and Q.
Why not plain SVD?
Singular value decomposition (SVD) is the classic way to get the best low-rank approximation of a complete matrix. It is tempting to apply it directly to R. That fails for two reasons:
Ris not complete. If you fill missing cells with 0, SVD treats those zeros as real ratings, as if every user hated every unseen item. The reconstruction is then pulled toward zero in exactly the cells you want to predict.- If you fill missing cells with the mean instead, you invent data. This also makes the matrix dense, which is costly for large catalogs.
Collaborative filtering factorization differs from textbook SVD in that it optimizes over observed entries only, and it adds regularization. People often call these models "SVD" in recommender papers, but the training procedure is not a classical SVD of a full matrix.
Adding biases
Some users rate everything high. Some items are rated high by everyone. A pure dot product has to spend factor capacity encoding these effects. A common refinement removes them explicitly:
r_hat(u, i) = mu + b_u + b_i + p_u · q_imuis the global mean rating.b_uis how much userudeviates from the mean.b_iis how much itemideviates from the mean.
The dot product then only explains the leftover interaction between this user and this item. Bias terms usually lower error noticeably for little extra cost, so they are a sensible default for explicit ratings.
Choosing k
The number of factors k controls model capacity.
- Too small: the model underfits and every user looks like a blend of a few archetypes.
- Too large: the model fits noise, trains more slowly, and needs stronger regularization.
Treat k and lambda as a pair. Pick them by evaluating on a validation split that was made without leakage, as covered in the earlier chapter on data splitting. Typical values are between 10 and 200 for large datasets. For the five-user example above, k = 2 is already enough.
Interpreting the factors
You should not expect factor 1 to mean "comedy". Two properties make the factors hard to read:
- The factorization is not unique. If
Ais any invertiblek × kmatrix, then(P @ A)and(Q @ inv(A).T)produce exactly the same predictions asPandQ. The axes can be rotated or mixed without changing a single score. - Factors can have either sign, and the model has no reason to align them with human concepts.
What you can rely on is geometry. Items whose vectors are close, measured by cosine similarity on the rows of Q, tend to be liked by the same users. This is a useful way to build item-to-item "similar items" lists from a trained model.
Common mistakes
- Counting missing cells as zeros in the loss. The model learns to predict that unrated items are disliked. Always use a mask or iterate over observed pairs.
- Evaluating on the training ratings. A model with a large
kcan score very well there and still recommend poorly. - Forgetting that
R_hatcovers items the user already rated. When producing a top-N list, exclude items the user has already seen. - Initializing all factors to zero. The gradient for every vector is then zero, and no learning happens. Use small random values, as in the code above.
Summary of the model
Matrix factorization assigns each user and each item a k-dimensional vector. The predicted rating is their dot product, optionally with global, user, and item bias terms. The loss counts observed ratings only and includes an L2 penalty. The result is a dense prediction matrix built from far fewer parameters than the raw matrix has cells.
Exercise
A catalog has 2,000 users and 800 items. You choose k = 10. How many parameters does a plain factorization model learn (no biases)? And why would setting every missing rating to 0 and fitting all cells be a poor idea?
Show answer
The model learns (2,000 + 800) × 10 = 28,000 parameters, compared with 1,600,000 matrix cells. Filling missing ratings with 0 and fitting all cells treats "not rated" as "rated zero". Because most cells are missing, the model would mostly learn to predict values near zero, which pulls predictions down for exactly the unrated items you want to rank. The loss should be computed only over observed ratings.
Exercise
A user's prediction vector is p = [1.0, 0.5] and an item's vector is q = [0.8, 1.2]. With mu = 3.0, bu = 0.4, and bi = -0.2, what is the predicted rating?
Show answer
The dot product is 1.0 × 0.8 + 0.5 × 1.2 = 1.4. Then r_hat = 3.0 + 0.4 + (-0.2) + 1.4 = 4.6.