Sub topic 10
Latent factors and matrix factorization
This chapter assumes you know basic Python, NumPy arrays, dot products, and the user-item matrix with its missing entries from earlier chapters.
The idea of latent factors
Neighborhood methods compare raw rating rows or columns. Matrix factorization takes a different route. It assumes each rating is explained by a few hidden traits, called latent factors. A latent factor is a number the model learns for each user and item. Nobody labels it. One factor might loosely track "action versus romance", but the model only finds whatever pattern fits the data.
Each user gets a vector of k numbers describing how much they like each trait. Each item gets a vector of k numbers describing how much it has each trait. The predicted rating is the dot product of the two vectors.
The factorization
Let R be the user-item matrix with n users and m items. Matrix factorization looks for two smaller matrices:
- P, with shape n × k, holds one row per user.
- Q, with shape m × k, holds one row per item.
Then R ≈ P Qᵀ. The prediction for user u and item i is pu · qi. Because k is much smaller than n or m, the model compresses the data. It must capture the main patterns and cannot memorize every entry.
Predicting from factors
The code below uses hand-picked factors with k = 2. It scores every user-item pair, then measures the error on observed ratings only.
import numpy as np
# 0 means "not rated".
R = np.array([
[5, 4, 0],
[0, 4, 1],
[1, 0, 5],
], dtype=float)
P = np.array([[1.0, 0.2], [0.9, 0.1], [0.1, 1.0]]) # users x k
Q = np.array([[5.0, 0.5], [4.5, 1.0], [0.5, 5.0]]) # items x k
scores = P @ Q.T
mask = R > 0
err = (R - scores) * mask
rmse = np.sqrt((err ** 2).sum() / mask.sum())
print(np.round(scores, 2))
print(f"RMSE on observed ratings = {rmse:.2f}")The multiplication P @ Q.T fills in every cell, including the ones where R has a 0. For example, user 0 gets a score of about 1.5 for item 2. These filled-in values are the recommendations.
Learning only from what was observed
A common error is to treat the 0 entries as real ratings of zero. That teaches the model that users dislike everything they have not seen. The training loss must sum over observed entries only. That is why the code multiplies the error by mask.
The usual objective is:
- Squared error on each observed rating.
- Plus an L2 penalty on the factor vectors, which keeps them small and reduces overfitting.
The next chapter covers how to minimize this objective.
Why it often beats neighborhood methods
- Two users who rated no items in common can still be close in factor space, so sparsity hurts less.
- Prediction is a single dot product, and you store n + m short vectors instead of a full similarity matrix.
- Factor vectors can be reused as features in other models.
Common errors
- Forgetting to mask missing entries in the loss.
- Initializing P and Q to all zeros. Every gradient is then identical or zero, so the factors never differentiate. Use small random values.
- Judging k by training error, which always improves as k grows.
- Expecting the factors to be interpretable. They are only defined up to rotation, so a single factor may not have a clean meaning.
Exercise
A teammate fills the 0 entries of R with the value 0 and minimizes squared error over the whole matrix. What goes wrong, and what change fixes it?
Show answer
The model treats unrated items as explicit zero ratings, so it learns to predict low scores for anything a user has not seen. The fix is to compute the loss only over observed entries, using a mask such as R > 0.
Exercise
R is 1,000 users by 500 items and k = 20. How many numbers do P and Q store together, and how does that compare with the 500,000 cells of R?
Show answer
P has 1,000 × 20 = 20,000 numbers and Q has 500 × 20 = 10,000, for 30,000 in total. That is 6% of the 500,000 cells of R.