Run one full alternating least squares sweep on observed ratings

Alternating least squares (ALS) factorises a sparse rating matrix by fixing item vectors and solving for every user exactly, then fixing users and solving for every item. Each sub-problem is a small ridge regression, so it parallelises well.

Write als_sweep(R, M, U, V, lam). R has shape (n_users, n_items), M is a 0/1 mask of the same shape (1 = observed rating), U has shape (n_users, k), V has shape (n_items, k), lam > 0. Only observed entries count. Missing entries are unknown, not zero.

1. For each user u, let O be the items with M[u, j] = 1. Set U[u] = solve(V_O.T @ V_O + lam * I, V_O.T @ R[u, O]). A user with no ratings gets the zero vector.
2. Then, using the NEW U, for each item j with observing users O: V[j] = solve(U_O.T @ U_O + lam * I, U_O.T @ R[O, j]).

Do not modify the inputs. Return (U_new, V_new) as NumPy arrays.

Signaturedef als_sweep(R, M, U, V, lam)

Understand the idea

Matrix factorisation guesses a rating as the dot product of a user vector and an item vector. Solving for both at once is hard, but if you freeze the item vectors, each user vector is just a small ridge regression with an exact answer. ALS alternates: solve every user with items fixed, then solve every item with the fresh users fixed. Only observed ratings enter each regression; a missing rating is unknown, not zero. Worked example with k = 1 and lam = 1: a user rated two items with vectors V = [2] and [1], ratings 4 and 3. Then V_O.T V_O = 4 + 1 = 5, plus lam gives 6, and V_O.T r = 2 * 4 + 1 * 3 = 11, so the user vector is 11 / 6 = 1.833. Rule: for user u, U[u] = solve(V_O^T V_O + lam * I, V_O^T r_O) over the items u rated; a user with none gets zeros. Then do the same for each item using the updated U and the users who rated it. Used in large-scale collaborative filtering because every row solves independently in parallel.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: user vectorsals_sweep(_R, _M, _U0, _V0, 0.1)[0]
  • Sample 2: item vectorsals_sweep(_R, _M, _U0, _V0, 0.1)[1]