Matrix factorization: fit the ratings you actually observed
推荐中的矩阵分解
Train biased latent factors with ridge ALS and compare mean, bias-only and rank-two predictions on held-out cells.
matrix-factorization-recsysA table with holes is not a fully observed matrix
A reader has rated three films, while thousands remain unseen. We want to predict preferences for the unseen films, but cannot treat every blank as a low rating. Nor should a generous rater’s high scores automatically mean that all their tastes differ from everyone else’s.
A biased matrix-factorization model separates a global mean, user generosity, item popularity in the rating scale, and a user–item interaction. The interaction uses short vectors learned jointly from observed ratings. Koren, Bell and Volinsky describe this model family and its regularized training. PDF 3–4 Here “popularity” in a bias is an average-rating tendency, not an interaction count.
This is not the operation “fill zeros, then call SVD.” Missing-data fitting specifies which errors count. Implicit feedback instead uses an all-pair objective with distinct weights; that difference changes the equations. Hu and colleagues, PDF 3–4
Hold one side fixed and solve a regression
For U users, I items and latent dimension d, let P and Q have shapes U-by-d and I-by-d. User bias a and item bias b are scalars per user or item. We predict:
The example fixes mu to the observed training mean. On observed positions Omega, it minimizes:
Our penalty counts each parameter once globally. Placing a penalty inside each observed-rating summand would multiply it by the user’s or item’s observation count; those conventions are not interchangeable at the same lambda. This is an explicitly chosen ridge objective, using the biased factor model discussed in the source. Unobserved entries contribute no error here. Regularized factors and biases, PDF 4
Fix all item parameters. For user u, form A_u with rows (1,q_i) for their observed items, target vector z_u with entries r_ui−mu−b_i, and parameter vector theta_u=(a_u,p_u). The user’s block is ordinary ridge regression. Its derivative is:
Setting the derivative to zero gives the update:
Solve this linear system; do not explicitly construct an inverse. The positive penalty makes its coefficient matrix positive definite, including when a user has no observations. That empty block solves to zero. Update each user, then exchange user and item roles and update each item. This is alternating least squares (ALS). Each exact block minimization cannot increase this objective, apart from floating-point error. Joint optimization remains nonconvex, so monotone training loss does not prove a global optimum.
For held-out cells T, report root mean squared error in the same units as the ratings:
Latent coordinates need not have unique semantic names. If R is orthogonal, rotating both sets of factors preserves predictions and the norm penalty:
A coordinate is therefore not automatically “love of science fiction.” Interpreting factors requires evidence beyond giving columns appealing names.
Compare three models on the same held-out cells
Run this original program with Python 3.12 and NumPy 1.26.4. A seeded rank-two model generates an 18-by-14 synthetic rating table; seed 14 also produces a random observation mask. There are 164 training cells and 88 held-out cells. The generator is intentionally well matched to the fitted model. Hyperparameters are fixed in the program, not selected on those held-out values.
"""Original biased matrix factorization with observed-only ridge ALS."""
import json
import numpy as np
def validate(ratings):
r = np.asarray(ratings, float)
if r.ndim != 2 or min(r.shape) == 0 or np.isinf(r).any() or not np.isfinite(r).any():
raise ValueError('nonempty matrix with finite observations or NaN required')
return r
def predict(model):
mu, bu, bi, p, q = model
return mu+bu[:,None]+bi[None,:]+p@q.T
def objective(ratings, model, regularization):
mask = np.isfinite(ratings); errors = (predict(model)-ratings)[mask]
return float(errors@errors+regularization*sum(np.sum(x*x) for x in model[1:]))
def fit(ratings, rank=2, regularization=.08, steps=40, seed=7):
r = validate(ratings)
if not isinstance(rank,int) or rank < 0 or not isinstance(steps,int) or steps < 0 or not np.isfinite(regularization) or regularization <= 0:
raise ValueError('nonnegative rank/steps and positive regularization required')
users,items = r.shape; rng = np.random.default_rng(seed)
mu = float(np.nanmean(r)); bu = np.zeros(users); bi = np.zeros(items)
p = rng.normal(0,.1,(users,rank)); q = rng.normal(0,.1,(items,rank))
model = (mu,bu,bi,p,q); history = [objective(r,model,regularization)]
penalty = regularization*np.eye(rank+1)
for _ in range(steps):
for u in range(users):
seen = np.isfinite(r[u]); design = np.column_stack([np.ones(seen.sum()),q[seen]])
solution = np.linalg.solve(design.T@design+penalty, design.T@(r[u,seen]-mu-bi[seen]))
bu[u],p[u] = solution[0],solution[1:]
history.append(objective(r,model,regularization))
for i in range(items):
seen = np.isfinite(r[:,i]); design = np.column_stack([np.ones(seen.sum()),p[seen]])
solution = np.linalg.solve(design.T@design+penalty, design.T@(r[seen,i]-mu-bu[seen]))
bi[i],q[i] = solution[0],solution[1:]
history.append(objective(r,model,regularization))
return model, history
def fixture():
rng = np.random.default_rng(14)
p = rng.uniform(-1,1,(18,2)); q = rng.uniform(-1,1,(14,2))
truth = 3+rng.uniform(-.2,.2,(18,1))+rng.uniform(-.2,.2,(1,14))+.6*p@q.T
mask = rng.random(truth.shape)<.65
return truth,np.where(mask,truth,np.nan),~mask
def demo():
truth,train,test = fixture(); baseline,_ = fit(train,rank=0); model,history = fit(train)
rmse = lambda prediction,mask:float(np.sqrt(np.mean((prediction[mask]-truth[mask])**2)))
mu = np.full(truth.shape,float(np.nanmean(train)))
return dict(train_count=int(np.isfinite(train).sum()),test_count=int(test.sum()),
history=history,train_rmse=rmse(predict(model),~test),
test_rmse=[rmse(mu,test),rmse(predict(baseline),test),rmse(predict(model),test)],
predictions=predict(model)[0].tolist(),truth=truth[0].tolist(),observed=(~test)[0].tolist())
if __name__=='__main__':print(json.dumps(demo(),allow_nan=False))
Training uses rank 2, lambda 0.08, 40 full alternating passes and initialization seed 7. The objective falls from about 16.703955 to 0.942672. Training RMSE is 0.018290. Held-out RMSE is 0.355893 for the global-mean baseline, 0.396902 for biases alone, and 0.110808 for biased rank-two factors. The bias-only model is worse than the mean here: adding parameters does not itself guarantee better held-out predictions.
The rank-zero baseline uses the same ALS machinery with no latent coordinates. Tests check each item block’s normal equation, loss monotonicity, empty rows and columns, a hand-computed regularization value, reproducibility and rotation invariance. Held-out values are used only to report errors, not to construct the training mean or update factors.
With sparse observation lists, one ALS pass costs approximately O(|Omega|(d+1)² + (U+I)(d+1)³) for Gram matrices and dense solves. This teaching program also scans the dense rating mask and materializes all U I predictions when logging the objective, adding O(U I(d+1)) work and O(U I) storage. Factors need O((U+I)d) storage. For a large table, use sparse observations and avoid evaluating every pair merely to log observed loss.
Fitting the table is not the whole recommendation task
Random synthetic holdout verifies a controlled prediction mechanism. It does not reproduce the selection process of real ratings or forecast future behavior. A real evaluation should specify its temporal split, unseen-user policy, candidate universe and ranking metrics. RMSE alone does not establish useful top-k recommendations.
An unseen user or item has no observations to identify its factor. Our empty-block rule returns zero factors and bias, leaving the remaining mean and known-side terms; it has not solved cold start. Content attributes or an explicit fallback supply additional information. Dense implicit interaction data also need a different interpretation: absent clicks are not missing explicit ratings with the same loss. Hu and colleagues, PDF 2–4
Change the objective, change the answer
- Why not replace every missing rating with zero? Answer: Doing so adds squared errors for previously unobserved cells. It changes the learning problem and pushes those predictions toward zero.
- An empty user’s block has positive lambda. What is its solution? Answer: Zero bias and factors, because both the design contribution and right-hand side vanish while lambda I remains invertible.
- Does a descending ALS objective prove the held-out RMSE must descend? Answer: No. ALS minimizes the regularized training objective; held-out error is a different quantity and may worsen.
- Both factor matrices are rotated by the same orthogonal matrix. What changes in predictions? Answer: Nothing; the rotations cancel in the dot products and preserve the norm penalty. Individual coordinate labels are consequently not uniquely identified.
Which part of matrix factorization was reproduced?
The reading covers observed-rating factorization, biases and SGD/ALS in the 2009 overview, and the contrasting weighted implicit formulation in Hu and colleagues. The executable example implements our stated global-penalty objective using exact block solves. It does not reproduce the Netflix data, competition results or a production recommender. A useful next experiment holds the split fixed while varying rank and regularization on a separate validation set, then reports the untouched test result once.
Make a prediction, then check
Does filling unseen ratings with zero preserve the observed-only objective?
Learning objectives
- Derive a block update and distinguish observed-only fitting from dense implicit objectives.
- Run the original example, check its numerical result and explain one failure condition.
Prerequisites & connections
Explore related knowledge →References
- Matrix Factorization Techniques for Recommender Systems
Yehuda Koren; Robert Bell; Chris Volinsky · 2009 - Collaborative Filtering for Implicit Feedback Datasets
Yifan Hu; Yehuda Koren; Chris Volinsky · 2008
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Physical PDF 1 identity, 2–4 methods text; viewed page 4 equations. Observed ratings, biases, SGD/ALS. No benchmark reproduction. Physical PDF 1 identity, 2 and 4 methods text, final 5500 characters of page 3; viewed page 4. Preference/confidence, all-pair objective and ALS. 6 paired equations and four explained exercises. Checked exact biased ALS blocks, normal equations, global-once penalty, monotonic objective, empty rows/columns and rotation invariance;164/88 synthetic split, fixed hyperparameters.
- Checked exact biased ALS blocks, normal equations, global-once penalty, monotonic objective, empty rows/columns and rotation invariance;164/88 synthetic split, fixed hyperparameters.
- Four computed SVG variants per topic;11 numeric/geometry tests and36 responsive cases passed. Twelve selected captures visually checked;11 current images match previously viewed bytes and the revised matrix-factorization image was viewed again. Full article acceptance recorded separately.
Source locations checked:
- Matrix Factorization Techniques for Recommender Systems · Physical PDF 1 identity, 2–4 methods text; viewed page 4 equations. Observed ratings, biases, SGD/ALS. No benchmark reproduction.
- Collaborative Filtering for Implicit Feedback Datasets · Physical PDF 1 identity, 2 and 4 methods text, final 5500 characters of page 3; viewed page 4. Preference/confidence, all-pair objective and ALS.
Related topics