Predict with a factorization machine in linear time

Why it matters Factorization machines and their deep variants are widely used for click-through prediction on sparse features.

Factorization machines model every pairwise feature interaction with a dot product of small factor vectors, which works well on sparse one-hot features like user id, item id and device.

Write fm_predict(X, w0, w, V). X is (B, n) features, w0 a float, w (n,), V (n, k). The prediction for row x is
w0 + w . x + sum over pairs i < j of (V[i] . V[j]) x_i x_j.
Compute the pair term in O(n k) with the identity 0.5 * sum over f of ((sum_i V[i, f] x_i)^2 - sum_i V[i, f]^2 x_i^2). Return a (B,) numpy array.

Signaturedef fm_predict(X, w0, w, V)

Example

fm_predict([[1, 1]], 0.5, [1, 2], [[1, 0], [1, 1]]) gives array([4.5]).

Understand the idea

Click prediction depends on combinations: a user may love cricket videos only on mobile. Learning a separate weight for every pair of features is hopeless when features are sparse one-hot ids, because most pairs are never seen together. A factorization machine gives each feature a small vector and models the pair weight as the dot product of the two vectors, so even unseen pairs get a sensible weight.

Example: two features both on, vectors [1, 0] and [1, 1], dot product 1. The linear part is 0.5 + 1 + 2 = 3.5, plus the pair term 1, total 4.5. With the trick: sum of vectors [2, 1] squared gives 5, sum of squared vectors gives 3, half the difference is 1.

Rule: y = w0 + w . x + 0.5 * sum_f ((sum_i v_if x_i)^2 - sum_i v_if^2 x_i^2).

The trick makes prediction linear in the number of features, which is why FMs scale to ad systems.

Shapes and data flow

X: (B, n), V: (n, k) -> X @ V: (B, k) -> pair term (B,) -> predictions (B,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplefm_predict([[1, 1]], 0.5, [1, 2], [[1, 0], [1, 1]])
  • Sample 2: one hotfm_predict([[1, 0, 0, 1, 0], [0, 1, 0, 0, 1]], 0.1, [0.2, -0.1, 0.0, 0.3, 0.05], [[0.5, 0.1], [0.2, -0.3], ...