Sub topic 11
Training with SGD and ALS
This chapter assumes you know basic Python and NumPy, dot products, and the idea of latent factors from the previous chapter. Matrix factorization approximates the rating matrix R with P @ Q.T. Here P holds one factor vector per user and Q holds one per item. Training means finding P and Q that fit the ratings you observed.
The objective
Only observed ratings count. Missing entries are unknown, not zero. The loss for a set of observed pairs (u, i) is:
sum (R[u,i] - P[u] · Q[i])² + reg * (‖P[u]‖² + ‖Q[i]‖²)
The regularization term (L2 penalty) shrinks factors toward zero. Without it, the model memorizes the few ratings each user has and predicts poorly on new pairs.
Stochastic gradient descent
SGD visits one observed rating at a time. It computes the error err = R[u,i] - P[u] · Q[i]. It then nudges P[u] and Q[i] along the negative gradient of the loss.
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)
def train_mf(R, k=2, lr=0.01, reg=0.05, epochs=200, seed=0):
rng = np.random.default_rng(seed)
n_users, n_items = R.shape
P = rng.normal(0, 0.1, (n_users, k))
Q = rng.normal(0, 0.1, (n_items, k))
users, items = np.nonzero(R)
for _ in range(epochs):
for idx in rng.permutation(len(users)):
u, i = users[idx], items[idx]
err = R[u, i] - P[u] @ Q[i]
pu = P[u].copy()
P[u] += lr * (err * Q[i] - reg * P[u])
Q[i] += lr * (err * pu - reg * Q[i])
return P, Q
P, Q = train_mf(R)
mask = R > 0
rmse = np.sqrt((((R - P @ Q.T) ** 2)[mask]).mean())
print(f"train RMSE = {rmse:.3f}")The code copies P[u] before updating it. Both updates must use the old value of P[u]. Shuffling each epoch avoids a fixed visiting order.
Alternating least squares
ALS uses a different idea. If you fix Q, the best P has a closed form. Each user's row is an ordinary ridge regression on the items that user rated. Then you fix P and solve for Q the same way, and repeat.
def als_step(R, fixed, reg=0.1):
k = fixed.shape[1]
out = np.zeros((R.shape[0], k))
for row in range(R.shape[0]):
idx = np.nonzero(R[row])[0]
if len(idx) == 0:
continue
F = fixed[idx]
A = F.T @ F + reg * np.eye(k)
out[row] = np.linalg.solve(A, F.T @ R[row, idx])
return out
rng = np.random.default_rng(0)
Q = rng.normal(0, 0.1, (R.shape[1], 2))
for _ in range(15):
P = als_step(R, Q)
Q = als_step(R.T, P)Choosing between them
| Aspect | SGD | ALS |
|---|---|---|
| Update | One rating at a time | Whole row via linear solve |
| Tuning | Learning rate, epochs | Fewer knobs, reg only |
| Parallelism | Harder, updates collide | Rows are independent |
| Cost per step | Cheap | Higher (k×k solve) |
Common errors
- Treating 0 as a real rating in the loss. Always use the observed mask.
- Setting the learning rate too high. The loss then grows or becomes
nan. - Skipping regularization, then seeing low training error but poor held-out error.
- Picking
kandregby looking at training RMSE. Use a validation split.
Exercise
In ALS, why can all user rows of P be solved in parallel when Q is fixed?
Show answer
With Q fixed, each user's loss depends only on that user's own row of P and the items they rated. The problems share no variables, so each row is a separate ridge regression.
Exercise
Your SGD training RMSE keeps falling but validation RMSE rises after epoch 40. What two changes could you try?
Show answer
Increase the regularization strength reg, reduce k, or stop training earlier (early stopping at epoch 40). Any two of these work.