Sub topic 11
Training with SGD and ALS
This chapter assumes you know the factorization model from the previous chapter: a rating is predicted as the dot product of a user vector and an item vector. It also assumes you are comfortable with NumPy, gradients at the level of "move against the slope", and solving a linear system.
The objective being minimized
Matrix factorization learns a user matrix P (one row per user) and an item matrix Q (one row per item), each with k columns. The predicted rating for user u and item i is P[u] @ Q[i].
Training minimizes squared error over the observed ratings only, plus an L2 penalty:
loss = sum over observed (u, i) of (r_ui - p_u . q_i)^2
+ reg * (|p_u|^2 + |q_i|^2)Two details matter.
- The sum runs over observed entries only. A
0in the matrix means "not rated", not "rated zero". If you fit the zeros, the model learns to predict that everything is missing. - The penalty keeps the factors small. Without it, a model with enough capacity memorizes the few ratings it sees and predicts badly on unseen pairs.
The loss is not convex in P and Q together. It is convex in P alone when Q is fixed, and in Q alone when P is fixed. SGD and ALS exploit the problem differently.
Stochastic gradient descent
SGD visits one observed rating at a time and nudges the two vectors involved. For one rating, let the error be e = r - p . q. The gradients of the per-rating loss are:
- with respect to
p:-2e*q + 2*reg*p - with respect to
q:-2e*p + 2*reg*q
Folding the constant 2 into the learning rate gives the update rules:
p <- p + lr * (e * q - reg * p)
q <- q + lr * (e * p - reg * q)Here is a complete script. It adds an RMSE helper that scores only observed entries.
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 rmse(R, P, Q):
mask = R > 0
err = (R - P @ Q.T)[mask]
return float(np.sqrt((err ** 2).mean()))
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 epoch 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])
if epoch % 50 == 0:
print(f"epoch {epoch}: train RMSE {rmse(R, P, Q):.3f}")
return P, Q
P, Q = train_mf(R)
print(f"final train RMSE {rmse(R, P, Q):.3f}")Four lines in the inner loop are easy to get wrong.
np.nonzero(R)builds the list of observed pairs, so unobserved cells are never touched.rng.permutationshuffles the order each epoch. Without shuffling, a sorted ratings file makes the model drift toward the last user it saw.pu = P[u].copy()stores the old user vector. The item update needs the value ofP[u]from before this step. If you skip the copy,Q[i]is updated with an already-modifiedP[u], which is a different (and unintended) algorithm.- The initial values are small random numbers, not zeros. With all-zero factors, both gradients are zero and nothing ever moves.
Choosing hyperparameters
| Parameter | Too small | Too large |
|---|---|---|
| `lr` | Training crawls | Error oscillates or becomes `nan` |
| `reg` | Overfits: train error low, validation error high | Underfits: all predictions drift toward zero |
| `k` | Cannot capture real taste differences | Overfits unless `reg` grows with it |
| `epochs` | Underfit | Overfit, wasted time |
Pick reg, k, and lr using a validation split, as covered in the data splitting chapter. Stop training when validation error stops improving (early stopping), not when training error stops improving.
Alternating least squares
ALS uses the convexity noted earlier. Fix Q. Then each user's vector p_u solves an independent ridge regression: predict that user's observed ratings from the vectors of the items they rated. The solution is closed-form:
p_u = (Q_u^T Q_u + reg * I)^-1 Q_u^T r_uQ_u holds the rows of Q for the items user u rated, and r_u holds those ratings. Then fix P and solve the same kind of problem for every item. Repeat. Each half-step cannot increase the loss, so the loss decreases monotonically.
Append this to the script above. It reuses R, rmse, and train_mf.
def train_als(R, k=2, reg=0.1, iters=20, 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))
mask = R > 0
eye = np.eye(k)
for _ in range(iters):
for u in range(n_users):
rated = mask[u]
if not rated.any():
continue
Qu = Q[rated]
P[u] = np.linalg.solve(Qu.T @ Qu + reg * eye, Qu.T @ R[u, rated])
for i in range(n_items):
raters = mask[:, i]
if not raters.any():
continue
Pi = P[raters]
Q[i] = np.linalg.solve(Pi.T @ Pi + reg * eye, Pi.T @ R[raters, i])
return P, Q
P_als, Q_als = train_als(R)
print(f"ALS train RMSE {rmse(R, P_als, Q_als):.3f}")Points to check in this code:
np.linalg.solveis used instead of an explicit matrix inverse. It is faster and numerically safer.- The
reg * eyeterm makes the matrix invertible even when a user rated fewer thankitems. Without it, a user with one rating gives a singular system. - Users or items with no ratings are skipped and keep their random initial vectors. Their predictions are meaningless, which is the cold start problem from a later chapter.
- This version applies a constant
reg. Some implementations scale it by the number of ratings per user or item ("weighted-lambda regularization"). That changes how much heavy users are shrunk, so compare results with care when you switch libraries.
SGD versus ALS
| Row | SGD | ALS |
|---|---|---|
| Update | Gradient step per rating | Exact solve per user or item |
| Hyperparameters | `lr`, `reg`, `k`, epochs | `reg`, `k`, iterations (no learning rate) |
| Cost per pass | Proportional to number of ratings | Proportional to ratings times `k^2`, plus a `k^3` solve per row |
| Parallelism | Awkward: updates share vectors | Easy: every user (then every item) is independent |
| Handles many implicit zeros | Needs negative sampling | Has a closed form that treats all cells efficiently |
| Flexibility | Any differentiable loss or extra term, such as biases | Tied to squared error |
Use SGD when you want flexibility, such as adding bias terms or other losses, and when the data fits comfortably on one machine. Use ALS when you want parallel training on a cluster, or when you move to implicit feedback, where the next chapter shows why ALS fits well.
Common errors
- Counting
0as a rating. Always build the observed mask from the original data, and watch for datasets where0is a legitimate rating. - Reporting training RMSE as model quality. Training error falls steadily with
kand epochs. Only held-out error shows generalization. - Using a learning rate copied from another dataset. If the loss rises or turns
nan, dividelrby 10. - Forgetting the
.copy()in SGD, as described above. - Using the same seed everywhere and concluding the result is stable. Different seeds give different local minima, so check the variance across a few seeds before comparing two settings.
Exercise
In the SGD update, why must you save a copy of P[u] before updating it?
Show answer
The update for Q[i] uses the user vector from before this step. P[u] += ... modifies the array in place. Without the copy, Q[i] would be updated with the new P[u], so the two updates would no longer be the gradient step on the same point.
Exercise
A user rated only one item and you run ALS with reg=0 and k=2. What goes wrong, and what fixes it?
Show answer
Qu.T @ Qu is a 2x2 matrix built from one row, so it has rank 1 and is singular. np.linalg.solve fails or returns unstable values. Setting reg > 0 adds reg * I to the matrix, which makes it invertible and shrinks the user vector toward zero.