AI Wiki中文/EN

Factorization machines: learn interactions without a coefficient for every pair

因子分解机

Expand the degree-two model, verify its efficient identity and train user-item-context interactions.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The same item can suit one situation and miss another

A user–item matrix records two identities. A recommendation request may also include time, device or a content category. Encoding user, item and context as features lets a model learn their interactions, but assigning a separate coefficient to every possible feature pair can leave many coefficients with almost no examples.

A degree-two factorization machine (FM) assigns each feature a short latent vector and obtains a pair coefficient from the vectors’ dot product. The same feature vector participates in many pairs, sharing parameters across those interactions. Rendle’s 2010 paper defines the model and an identity that evaluates its quadratic term without enumerating all feature pairs. PDF 2–3

This article implements squared-loss regression with a two-way FM. The model family also permits other losses and higher-order terms; neither a click classifier nor a deep network is implied by the name.

A trained two-way FM fits synthetic interactions; the held-out comparison is not a public benchmark.
A trained two-way FM fits synthetic interactions; the held-out comparison is not a public benchmark.

Expand a square, then remove its diagonal

Let x have n features, w contain n linear weights, and V contain one k-dimensional row v_i per feature. The prediction is:

y^(x)=b+∑i=1nwixi+∑i<j⟨vi,vj⟩xixj.\widehat y(x)=b+\sum_{i=1}^{n}w_ix_i+\sum_{i<j}\langle v_i,v_j\rangle x_ix_j.

There are n k factor parameters instead of an independently learned coefficient for each of the n(n−1)/2 pairs. This sharing constrains the interactions; it does not make every possible pairwise coefficient table representable with a small k.

For each latent coordinate f, square the weighted sum. It contains diagonal terms and twice each unordered pair. Subtract the diagonal and divide by two:

∑i<j⟨vi,vj⟩xixj=12∑f=1k[(∑ivifxi)2−∑ivif2xi2].\sum_{i<j}\langle v_i,v_j\rangle x_ix_j=\frac12\sum_{f=1}^{k}\left[\left(\sum_i v_{if}x_i\right)^2-\sum_i v_{if}^2x_i^2\right].

Both sums can be accumulated over nonzero features, so prediction takes O(k m) when x has m active features, instead of O(k m²) explicit pair enumeration. The paper derives this identity and its derivatives. PDF 3 Our NumPy implementation uses dense matrices, so its actual per-row work is O(n k), even when many entries are zero.

For N training rows, we minimize an averaged squared loss with regularized linear weights and factors, leaving b unpenalized:

L=12N∑a=1N(y^(xa)−ya)2+λ2(∥w∥22+∥V∥F2).L=\frac{1}{2N}\sum_{a=1}^{N}(\widehat y(x_a)-y_a)^2+\frac{\lambda}{2}(\|w\|_2^2+\|V\|_F^2).

Write the residual as e_a and the latent sum as s_af. Differentiating the efficient identity gives:

∂y^(xa)∂vif=xai(saf−vifxai),saf=∑jvjfxaj.\frac{\partial\widehat y(x_a)}{\partial v_{if}}=x_{ai}\left(s_{af}-v_{if}x_{ai}\right),\qquad s_{af}=\sum_jv_{jf}x_{aj}.

The gradient of the training objective is consequently:

∂L∂b=1N∑aea,∂L∂wi=1N∑aeaxai+λwi,∂L∂vif=1N∑aeaxai(saf−vifxai)+λvif.\frac{\partial L}{\partial b}=\frac1N\sum_a e_a,\quad\frac{\partial L}{\partial w_i}=\frac1N\sum_a e_ax_{ai}+\lambda w_i,\quad\frac{\partial L}{\partial v_{if}}=\frac1N\sum_a e_ax_{ai}(s_{af}-v_{if}x_{ai})+\lambda v_{if}.

Subtract a learning-rate multiple of these gradients to update the parameters. If every factor is initialized to zero, both s and the interaction gradient stay zero. Small random nonzero factors allow interaction learning to begin; the libFM manual also documents nonzero factor initialization options. Manual, PDF 7

Encode a user and item with distinct one-hot fields. Exactly two entries are 1, so only their pair interaction survives:

y^(u,i)=b+wu+wi+⟨vu,vi⟩.\widehat y(u,i)=b+w_u+w_i+\langle v_u,v_i\rangle.

This recovers a biased matrix-factorization predictor. Add a one-hot context field and user–context and item–context pair terms also appear. A degree-two FM does not add a separate three-way user–item–context product.

Verify both the identity and the learning

The original complete program runs with Python 3.12 and NumPy 1.26.4. It encodes 4 users, 5 items and 2 contexts in 11 disjoint one-hot features. Each of the 40 combinations has three active entries. A seeded FM generates the targets: these are synthetic regression values, not human ratings or click probabilities. Every fifth row is held out, leaving 32 training rows and 8 test rows.

"""Original dense degree-two factorization machine with analytic batch gradients."""
import itertools
import json
import numpy as np


def predict(x,model):
    x=np.asarray(x,float); b,w,v=model
    if x.ndim!=2 or w.shape!=(x.shape[1],) or v.ndim!=2 or v.shape[0]!=x.shape[1] or not all(np.isfinite(a).all() for a in (x,w,v)) or not np.isfinite(b):
        raise ValueError('finite compatible feature/model arrays required')
    return b+x@w+.5*np.sum((x@v)**2-(x*x)@(v*v),axis=1)


def objective_gradient(x,y,model,regularization=.001):
    x=np.asarray(x,float);y=np.asarray(y,float);prediction=predict(x,model);b,w,v=model
    if y.shape!=prediction.shape or not len(y) or not np.isfinite(y).all() or not np.isfinite(regularization) or regularization<0:
        raise ValueError('finite targets and nonnegative regularization required')
    error=prediction-y;n=len(y)
    loss=.5*float(error@error)/n+.5*regularization*float(np.sum(w*w)+np.sum(v*v))
    gradient=(float(error.mean()),x.T@error/n+regularization*w,
              x.T@(error[:,None]*(x@v))/n-v*((x*x).T@error/n)[:,None]+regularization*v)
    return loss,gradient


def fit(x,y,rank=2,steps=1000,rate=.1,regularization=.001,seed=8):
    x=np.asarray(x,float);y=np.asarray(y,float)
    if x.ndim!=2 or not isinstance(rank,int) or rank<1 or not isinstance(steps,int) or steps<0 or not np.isfinite(rate) or rate<=0:
        raise ValueError('matrix features and valid optimizer controls required')
    rng=np.random.default_rng(seed);model=(0.,np.zeros(x.shape[1]),rng.normal(0,.1,(x.shape[1],rank)))
    history=[]
    for step in range(steps+1):
        loss,gradient=objective_gradient(x,y,model,regularization);history.append(loss)
        if step<steps:model=tuple(a-rate*g for a,g in zip(model,gradient))
    return model,history


def fixture():
    cases=list(itertools.product(range(4),range(5),range(2)));x=np.zeros((len(cases),11))
    for row,(user,item,context) in enumerate(cases):x[row,[user,4+item,9+context]]=1
    rng=np.random.default_rng(21)
    truth=(3.,rng.normal(0,.1,11),rng.normal(0,.5,(11,2)))
    y=predict(x,truth);test=np.arange(len(x))%5==0
    return x,y,test


def demo():
    x,y,test=fixture();model,h=fit(x[~test],y[~test]);prediction=predict(x,model)
    linear=np.linalg.lstsq(np.column_stack([np.ones((~test).sum()),x[~test]]),y[~test],rcond=None)[0]
    linear_pred=np.column_stack([np.ones(test.sum()),x[test]])@linear
    hand=(.2,np.array([.5,-.5,1.]),np.array([[1.,2.],[2.,-1.],[1.,1.]]))
    return dict(train_count=int((~test).sum()),test_count=int(test.sum()),loss=[h[0],h[-1]],
                train_rmse=float(np.sqrt(np.mean((prediction[~test]-y[~test])**2))),
                test_rmse=[float(np.sqrt(np.mean((linear_pred-y[test])**2))),float(np.sqrt(np.mean((prediction[test]-y[test])**2)))],
                hand_prediction=float(predict(np.array([[1.,2.,0.]]),hand)[0]),
                predictions=prediction[test].tolist(),targets=y[test].tolist())


if __name__=='__main__':print(json.dumps(demo(),allow_nan=False))

With target seed 21, initialization seed 8, rank 2, learning rate 0.1, lambda 0.001 and 1000 batch updates, training loss falls from 4.690299 to 0.004065. Training RMSE is 0.037272. Held-out RMSE is 0.701589 for unregularized linear least squares and 0.193547 for the FM. This fixture favors a model capable of representing its generating interactions; it does not establish a general advantage on recommendation datasets. The same held-out rows are used for both models, and no hyperparameter search is performed on them.

For a hand check, use x=(1,2), b=0.2, w=(0.5,−0.5), and factor rows (1,2) and (2,1). Their dot product is 4, so the interaction is 8 and the total is 7.7. The printed demo uses a different second factor, (2,−1), whose dot product is zero; its total is −0.3. Keeping these cases separate makes an interaction visible instead of silently changing a coefficient to match an expectation.

Tests compare the efficient prediction with explicit pair loops, check finite differences for every scalar parameter, recover the two-hot matrix-factorization case and show that zero factors cannot start learning. A full dense gradient pass costs O(N n k) time and roughly O(N n + N k + n k) storage with its intermediates. The program stores a scalar loss per iteration. Large sparse inputs need sparse accumulation and usually minibatches; merely storing feature IDs does not make this dense implementation sparse.

Sharing a vector is a modeling restriction

One feature uses the same latent vector when meeting user, item or context features. That can transfer evidence, but also forces different interaction types to share a representation. More factors increase capacity and cost; they do not guarantee generalization. Gradient descent on the factorized objective is nonconvex, and a fixed step size need not decrease the loss on arbitrary inputs.

Stable feature identities are essential. The libFM manual specifies sparse index–value data and consistent indices across training and test files. PDF 3 Accidentally using the same index for an item and a device merges two meanings. A completely unseen ID also has no trained latent vector; parameter sharing helps through features already learned, not through an unknown identity alone. Check time splits, feature availability and cold-start handling in the surrounding system.

Predict the interaction before running it

  1. What does k control? Answer: The length of each feature’s latent vector and the capacity of their shared pairwise coefficients. It is not the number of output recommendations.
  2. In the hand example with factor dot product 4 and active values 1 and 2, what is the interaction? Answer: 8. Adding the intercept and linear term gives 0.2+0.5−1+8=7.7.
  3. Why does all-zero factor initialization fail to learn interactions under this gradient? Answer: Every latent sum and factor is zero, so every factor derivative is zero. Linear weights can still learn, but the interaction factors remain stuck.
  4. With active user, item and context features, does a degree-two FM learn an explicit three-way term? Answer: No. It includes user–item, user–context and item–context pairs. A three-way interaction requires a changed model.

Read the model separately from the software

The paper’s physical pages 2–3 supply the degree-two equations, computational identity and derivative; page 3 was also viewed. The libFM 1.4.2 manual, dated September 14, 2014, supplies feature-index and initialization details. Our batch optimizer and synthetic test are original, not copied from libFM or represented as reproducing its benchmarks. The upstream repository’s GPL license is recorded as a reference; no upstream code was incorporated.

Make a prediction, then check

Why avoid initializing every latent factor to zero?

Choose one answer

Learning objectives

  • Derive the interaction gradient and recover matrix factorization as a two-hot special case.
  • Run the original example, check its numerical result and explain one failure condition.

Prerequisites & connections

Explore related knowledge →

References

  1. Factorization Machines
    Steffen Rendle · 2010
  2. libFM 1.4.2 Manual — September 14, 2014
    Steffen Rendle · 2014

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–3 full method text; viewed page 3 equations. Degree-two model, linear computation identity and derivative; no benchmark reproduction. Physical PDF 1 identity, 3 and 7 text: sparse feature indices and learning/initialization options. No upstream code executed or copied. 6 paired equations and four explained exercises. Checked degree-two identity by explicit pair loops, every parameter by finite differences, zero-factor stagnation, two-hot MF equivalence and actual batch training;32/8 FM-generated synthetic split.

  • Checked degree-two identity by explicit pair loops, every parameter by finite differences, zero-factor stagnation, two-hot MF equivalence and actual batch training;32/8 FM-generated synthetic split.
  • 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:

  • Factorization Machines · Physical PDF 1 identity, 2–3 full method text; viewed page 3 equations. Degree-two model, linear computation identity and derivative; no benchmark reproduction.
  • libFM 1.4.2 Manual — September 14, 2014 · Physical PDF 1 identity, 3 and 7 text: sparse feature indices and learning/initialization options. No upstream code executed or copied.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.