Take one SGD step of matrix factorisation

Matrix factorisation learns a vector for each user and each item so that their dot product predicts the rating. Training is plain SGD over observed ratings.

Write mf_step(U, V, ratings, lr, reg) where ratings is a list of (user, item, value). Process them in order. For each one:
err = value - U[u] @ V[i]
U[u] += lr * (err * V[i] - reg * U[u])
V[i] += lr * (err * U[u]_old - reg * V[i])
Use the user vector from BEFORE its update when updating V[i]. Return new (U, V) without modifying the inputs.

Signaturedef mf_step(U, V, ratings, lr, reg)

Understand the idea

Matrix factorisation gives every user and every item a short vector, and their dot product should predict the rating. Training walks through observed ratings and nudges both vectors to shrink the error, with a small pull toward zero (regularisation). Both nudges come from the same error, so both must use the parameter values from before this rating's update. Worked example, lr = 0.1, reg = 0: U[0] = [1, 0], V[0] = [1, 1], rating 3. Prediction = 1, err = 2. New U[0] = [1, 0] + 0.1 x 2 x [1, 1] = [1.2, 0.2]. New V[0] = [1, 1] + 0.1 x 2 x [1, 0] (old U) = [1.2, 1.0]. Using the new U by mistake would give [1.24, 1.04]. Rule: err = r - U[u] . V[i]; U[u] += lr (err V[i] - reg U[u]); V[i] += lr (err U_old - reg V[i]). Process ratings in order and work on copies. The Netflix Prize era recommenders were built on this.

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

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

  • Sample 1: users after one passmf_step(_U, _V, _rt, 0.1, 0.01)[0]
  • Sample 2: items after one passmf_step(_U, _V, _rt, 0.1, 0.01)[1]