Sub topic 12
Factorization for implicit feedback
This chapter assumes you have read the earlier chapters on explicit versus implicit feedback, the user-item matrix, and SGD-based matrix factorization. You should be comfortable with NumPy and with solving small linear systems.
Why explicit-feedback factorization breaks on implicit data
The SGD model from the previous chapter fits only the observed cells of the matrix. That works for star ratings because every observed cell carries a clear signal, such as "this user gave 4 stars". The unobserved cells are simply unknown.
Implicit data changes this in two ways:
- There is no negative signal. A play count of 12 says the user probably likes the item. A missing entry could mean dislike, or it could mean the user never saw the item.
- Observed values are noisy. A single play might be an accident, while 40 plays is strong evidence. The count measures how sure we are, not how much the user likes the item.
If you fit only the observed cells, the model sees only positives and can score everything high. If you treat every zero as a hard "rating of 0", you tell the model the user dislikes every item they haven't met. Implicit factorization avoids both mistakes by using all cells, with different weights.
Preference and confidence
The standard formulation comes from Hu, Koren and Volinsky (2008). It splits each raw interaction value r_ui into two quantities:
- Preference
p_uiis 1 ifr_ui > 0, otherwise 0. It is the binary target. - Confidence
c_ui = 1 + alpha * r_uiis a weight. Unobserved cells get confidence 1. Observed cells get more, growing with the count.
The model learns user vectors x_u and item vectors y_i by minimizing a weighted squared error over every user-item pair:
sum over all (u, i) of c_ui * (p_ui - x_u · y_i)^2 + lambda * (sum of ||x_u||^2 + sum of ||y_i||^2)
An unobserved cell still pulls the prediction toward 0, but weakly. An item played many times pulls hard toward 1. The hyperparameter alpha controls how much extra weight observed interactions get.
| Quantity | Explicit MF | Implicit MF |
|---|---|---|
| Target | the rating | binary preference 0 or 1 |
| Cells in the loss | observed only | all cells |
| Role of the raw value | the thing to predict | sets the confidence weight |
| Typical solver | SGD | ALS (or SGD with sampling) |
Raw counts are often heavy-tailed, so one user with 5,000 plays of a song can dominate the loss. A common fix is to dampen the count, for example c = 1 + alpha * log(1 + r / eps). Treat the form of the confidence function as a tunable choice.
Why ALS fits this problem
The loss now covers every cell, which is n_users * n_items terms. For a catalog of a million items, the SGD approach from the previous chapter would have to visit all of them. The only way to stay cheap is to sample unobserved cells, which adds noise.
Alternating least squares (ALS) takes a different route. If you fix all item vectors Y, the loss is quadratic in each user vector, so each x_u has a closed-form solution:
x_u = (Y^T C^u Y + lambda I)^(-1) Y^T C^u p(u)
Here C^u is a diagonal matrix holding user u's confidences over all items. The same formula, with roles swapped, gives each y_i when X is fixed.
The naive cost of forming Y^T C^u Y is proportional to the number of items. The paper's trick is to rewrite it:
Y^T C^u Y = Y^T Y + Y^T (C^u - I) Y
The matrix C^u - I is zero for every item the user did not interact with. So you compute Y^T Y once per sweep and add a correction using only that user's observed items. The cost per user then scales with how many items they touched, not with the catalog size. The dense code below does not use this shortcut, to keep it readable. Production libraries do.
A runnable implementation
The following code implements dense implicit ALS on a small play-count matrix. Users 0 to 2 listen to items 0 to 2, and users 3 and 4 listen to items 3 to 5. User 0 has never played item 2.
import numpy as np
def solve_side(F, C, P, reg):
"""Solve every row vector given fixed factors F.
F: (n_other, k) fixed factors
C: (n_rows, n_other) confidence
P: (n_rows, n_other) binary preference
"""
k = F.shape[1]
FtF = F.T @ F
out = np.zeros((C.shape[0], k))
for row in range(C.shape[0]):
c = C[row]
A = FtF + F.T @ ((c - 1.0)[:, None] * F) + reg * np.eye(k)
b = F.T @ (c * P[row])
out[row] = np.linalg.solve(A, b)
return out
def implicit_als(R, k=2, alpha=10.0, reg=0.1, iters=15, seed=0):
rng = np.random.default_rng(seed)
n_users, n_items = R.shape
X = rng.normal(0, 0.1, (n_users, k))
Y = rng.normal(0, 0.1, (n_items, k))
P = (R > 0).astype(float)
C = 1.0 + alpha * R
for _ in range(iters):
X = solve_side(Y, C, P, reg)
Y = solve_side(X, C.T, P.T, reg)
return X, Y
def recommend(X, Y, R, user, n=2):
scores = X[user] @ Y.T
scores[R[user] > 0] = -np.inf # never re-recommend seen items
return np.argsort(scores)[::-1][:n]
R = np.array([
[5, 3, 0, 0, 0, 0],
[4, 0, 2, 0, 0, 0],
[6, 2, 3, 0, 0, 0],
[0, 0, 0, 7, 1, 4],
[0, 0, 0, 2, 5, 3],
], dtype=float)
X, Y = implicit_als(R)
print(recommend(X, Y, R, user=0))Because the matrix has two clear groups, item 2 should rank above items 3 to 5 for user 0. Exact scores depend on the seed and on k.
Notice the line that sets seen items to negative infinity. The model is trained to predict that seen items have preference 1, so they would otherwise fill the top of every list. Recommendation usually means "what to show next", so you filter them out. Re-recommending is appropriate only in some domains, such as groceries.
Hyperparameters that matter
alphasets how much more an observed interaction counts than an unobserved one. Values from 1 to 100 are common, and you tune it on validation data. Too low and the model collapses toward all-zero predictions. Too high and it overfits the few observed cells.kis the number of latent factors. As with explicit MF, more factors mean more capacity and more overfitting risk. Implicit models often use 50 to 200 on real data.regis the L2 penalty. Because the loss now includes every cell, the scale of the data term is larger than in explicit MF. A regularization value that worked before may now be too weak.itersis usually 10 to 20 sweeps. Each ALS step cannot increase the loss, so it converges steadily.
Alternatives: ranking losses
The weighted-regression approach predicts a 0/1 target. Another family optimizes the ranking of items directly. Bayesian Personalized Ranking (BPR) samples triples (u, i, j) where i was interacted with and j was not. It trains the model so that x_u · y_i > x_u · y_j. It uses SGD, handles huge catalogs through sampling, and matches the top-N goal more closely. The trade-off is that sampling choices, especially how you pick j, strongly affect quality and popularity bias.
Evaluation and common errors
Use the leakage-safe splits and the ranking metrics from the earlier chapters. RMSE is meaningless here because the model does not predict a rating. Measure precision@k, recall@k, or NDCG on held-out interactions.
Common errors:
- Evaluating on seen items. If you do not mask training items before ranking, the metric mostly measures memorization.
- Treating a held-out zero as a true negative. An item the user never saw but would have liked counts against you. Ranking metrics are therefore pessimistic, so compare models against each other, not against an absolute target.
- Skipping count transformation. Raw counts with a heavy tail let a few users and items dominate.
- Reusing explicit-MF hyperparameters. The loss has changed, so retune
regandk. - Dense matrices at scale. The dense
Rhere is only for teaching. Real data needs sparse storage and theY^T Yshortcut.
Exercises
Exercise
A user has played a song 3 times. With alpha = 40, what are the preference and the confidence for that cell, and what are they for a song the user never played?
Show answer
For the played song, preference is 1 and confidence is 1 + 40 3 = 121. For the unplayed song, preference is 0 and confidence is 1 + 40 0 = 1. The unplayed cell still contributes to the loss, but with 121 times less weight.
Exercise
Why does implicit MF train on all cells of the matrix, while explicit SGD MF trains only on observed cells? What trick keeps ALS affordable on large catalogs?
Show answer
With implicit data, a zero is ambiguous: it may mean dislike or lack of exposure. Training only on observed cells would show the model only positives. Including all cells with low confidence on unobserved ones supplies a weak pull toward "not preferred". ALS stays affordable by rewriting Y^T C^u Y as Y^T Y + Y^T (C^u - I) Y. Y^T Y is computed once per sweep, and the correction only involves the items that user interacted with, because C^u - I is zero elsewhere.