Overview
Click data is mostly categorical: a user id, an item id, a context. What matters is often the pair, such as this user with this kind of item, but most pairs never appear in the training data. A factorization machine handles this by giving every value a short vector and scoring a pair by the dot product of the two vectors. Since each vector is learned from all the rows its value appears in, the model can score pairs it has never seen. DeepFM adds a deep network that reads the same vectors to catch patterns involving more than two fields, and sums the two scores.
A short history
Steffen Rendle introduced factorization machines in 2010 to model pairwise feature interactions through embeddings. Huifeng Guo and colleagues at Huawei's Noah's Ark Lab published DeepFM in 2017, joining a factorization machine and a deep network on one shared set of embeddings. Unlike Wide & Deep, it needs no hand-built cross features, and the authors evaluated it on app store data.
How it works
- For each field, look up the value's weight and its latent vector .
- First-order part: add the global bias and the weights of all the fields.
- Second-order part (the factorization machine): add the dot product of every pair of field vectors.
- Deep part: concatenate the field vectors and pass them through a ReLU MLP that outputs one number.
- Add the three parts and apply the sigmoid to get the click probability.
- Train weights, vectors and the MLP together with Adam on the binary cross-entropy loss. Both parts update the same vectors.
Watch out for
- A value seen only a few times has a latent vector close to its random start, so its pair scores are unreliable. Rare values are often grouped into one shared id.
- The deep part can overfit small datasets, because it has far more weights than the FM. Try
use_deep=Falsefirst and compare. - The FM and the deep part pull on the same embeddings. A large
embedding_sizehelps the deep part but gives the FM more room to fit noise in rare pairs. - This template takes one id per field and has no numeric or multi-valued fields, and it updates embeddings densely, so it suits vocabularies up to tens of thousands of ids.
Use cases
When to use it
Click or conversion data made of categorical fields where pairs of fields matter and most pairs are never seen together. Use the FM alone on small data, and add the deep part when there is enough data.
In industry
- App stores
- Predicting which app a user will download, the setting the original paper evaluated.
- Online advertising
- Click-through rate prediction from sparse features such as user id, ad id, device and placement.
- Content feeds
- Ranking articles or videos by predicted click from user, item and context ids.
Choosing it: what must hold
- Sparse categorical features arranged in fields, such as user, item and context.
- A binary target such as click or no click, with a large interaction log.
- Signal in pairwise interactions between fields.
When to choose something else
| If | Use instead |
|---|---|
| Interactions beyond pairs matter and you can afford more capacity | Deep & Cross Network (DCN) |
| You have known, important cross features to memorise | Wide & Deep |
| The user's behaviour sequence is the main signal | Deep Interest Network (DIN) |
Math foundations
Factorization machine
A bias, one weight per active value, and one dot product per pair of fields. The pair weight is not a free parameter: it is built from two vectors, so it can be estimated even for unseen pairs.
Computing all pairs in linear time
The square of a sum contains every pair twice plus the squares. Removing the squares and halving leaves the pairs. This costs where the direct sum costs .
Deep part
A ReLU network over the same vectors, joined end to end. It can represent interactions of more than two fields.
Prediction and loss
The two scores are added before the sigmoid, and the model is trained on the binary cross-entropy.
Gradient of the FM term
Each vector is moved in the direction of the sum of the other fields' vectors, scaled by the prediction error. Values that occur together in clicked rows become aligned.
Symbols
- number of categorical fields
- the id of field f in this row
- global bias
- first-order weight of that id
- latent vector (embedding) of that id; written v_f for short
- embedding_size
- dot product
- the sigmoid function
- predicted click probability and true label
Worked by hand
Three fields with vectors , and . Compute the second-order term both ways.
Both routes give 2. The second needs one pass over the fields and no pairs, which is why the template's fm_second_order uses it.
Visual example
Loading the example.
Try this
- Ben with the heist film was never shown in training. Compare the model's answer for that pair with the true rate.
- Switch the model to first-order only and watch the whole table lose its pattern.
- Hold out more of Ben's row, one pair at a time, and see how few pairs his vector needs.
Code sample
import numpy as np
from impl import DeepFM
from config import DeepFMConfig
rng = np.random.default_rng(0)
X = rng.integers(0, 8, size=(1500, 2)) # two categorical fields, one id each
y = ((X[:, 0] + X[:, 1]) % 2 == 0).astype(int) # click depends on the pair, not on either field
model = DeepFM(DeepFMConfig(epochs=15, learning_rate=0.02)).fit(X, y)
print((model.predict(X) == y).mean()) # close to 1.0
print(model.predict_proba(X[:3]))Read the implementation (180 lines)
"""DeepFM: a factorization machine and a deep network that share one set of feature embeddings.
NumPy only, manual backpropagation. For a row with one active id per field:
logit = bias + sum_f w[f] first-order (linear) term
+ sum_{f < g} <v_f, v_g> FM second-order term, every pair of fields
+ MLP(concat_f v_f) deep term, higher-order interactions
The pairwise sum is computed in O(F k) with the identity 0.5 * ((sum_f v_f)^2 - sum_f v_f^2).
"""
from __future__ import annotations
import numpy as np
try:
from .config import DeepFMConfig
except ImportError: # run from the template's own folder
from config import DeepFMConfig
def _sigmoid(z: np.ndarray) -> np.ndarray:
return 1.0 / (1.0 + np.exp(-np.clip(z, -60.0, 60.0)))
def _mlp_init(params: dict, prefix: str, sizes: list, rng: np.random.Generator) -> None:
"""Add the layers of an MLP to `params` as `<prefix>W<i>` (fan_in, fan_out) and `<prefix>b<i>` (fan_out,)."""
for i, (a, b) in enumerate(zip(sizes[:-1], sizes[1:])):
params[f"{prefix}W{i}"] = rng.normal(0.0, np.sqrt(2.0 / a), size=(a, b))
params[f"{prefix}b{i}"] = np.zeros(b)
def _mlp_forward(params: dict, prefix: str, x: np.ndarray, n_layers: int, last_linear: bool) -> list:
"""Run an MLP with ReLU layers on x (..., fan_in). Returns every activation, the input first.
last_linear: leave the last layer without ReLU (used when it produces a logit or a score).
"""
acts = [x]
for i in range(n_layers):
z = acts[-1] @ params[f"{prefix}W{i}"] + params[f"{prefix}b{i}"]
acts.append(z if (last_linear and i == n_layers - 1) else np.maximum(z, 0.0))
return acts
def _mlp_backward(params: dict, prefix: str, acts: list, d: np.ndarray, grads: dict, last_linear: bool) -> np.ndarray:
"""Backpropagate d (gradient at the MLP output) and store the weight gradients. Returns the input gradient."""
n_layers = len(acts) - 1
for i in range(n_layers - 1, -1, -1):
if not (last_linear and i == n_layers - 1):
d = d * (acts[i + 1] > 0)
a = acts[i].reshape(-1, acts[i].shape[-1])
grads[f"{prefix}W{i}"] = a.T @ d.reshape(-1, d.shape[-1])
grads[f"{prefix}b{i}"] = d.reshape(-1, d.shape[-1]).sum(axis=0)
d = d @ params[f"{prefix}W{i}"].T
return d
def _bce(logit: np.ndarray, y: np.ndarray) -> tuple[float, np.ndarray]:
"""Mean binary cross-entropy from logits, and its gradient with respect to the logits. Both inputs (n,)."""
loss = float(np.mean(np.logaddexp(0.0, logit) - y * logit))
return loss, (_sigmoid(logit) - y) / len(y)
def _adam_fit(model, arrays: tuple, y: np.ndarray) -> None:
"""Mini-batch Adam over `model.params` using `model.loss_and_grads(*batch_arrays, batch_y)`."""
cfg = model.config
rng = np.random.default_rng(cfg.seed + 1)
m = {k: np.zeros_like(p) for k, p in model.params.items()}
v = {k: np.zeros_like(p) for k, p in model.params.items()}
step = 0
model.loss_history = []
for _ in range(cfg.epochs):
order = rng.permutation(len(y))
total = 0.0
for start in range(0, len(y), cfg.batch_size):
rows = order[start:start + cfg.batch_size]
loss, grads = model.loss_and_grads(*[a[rows] for a in arrays], y[rows])
total += loss * len(rows)
step += 1
for name, g in grads.items():
m[name] = 0.9 * m[name] + 0.1 * g
v[name] = 0.999 * v[name] + 0.001 * g * g
model.params[name] -= cfg.learning_rate * (m[name] / (1 - 0.9**step)) / (
np.sqrt(v[name] / (1 - 0.999**step)) + 1e-8)
model.loss_history.append(total / len(y))
def _field_offsets(X_sparse: np.ndarray, field_dims) -> tuple[tuple, np.ndarray]:
"""Resolve the vocabulary size of each sparse field and the row offset of each field in a shared table.
X_sparse: (n, F) non-negative integer ids. field_dims: sizes from the config, or None to take max id + 1.
"""
if X_sparse.ndim != 2 or (X_sparse.size and X_sparse.min() < 0):
raise ValueError("X_sparse must be a 2-d array of non-negative integer ids")
dims = tuple(int(d) for d in (field_dims if field_dims is not None else X_sparse.max(axis=0) + 1))
if len(dims) != X_sparse.shape[1]:
raise ValueError(f"field_dims has {len(dims)} entries but X_sparse has {X_sparse.shape[1]} columns")
return dims, np.concatenate([[0], np.cumsum(dims)[:-1]]).astype(int)
def fm_second_order(V: np.ndarray) -> np.ndarray:
"""Sum of the dot products of every pair of field vectors. V: (n, F, k) -> (n,)."""
s = V.sum(axis=1)
return 0.5 * np.sum(s**2 - np.sum(V**2, axis=1), axis=1)
class DeepFM:
"""Click-through-rate model over categorical fields. `use_fm` and `use_deep` switch the two parts.
With `use_deep=False` it is a plain factorization machine.
"""
def __init__(self, config: DeepFMConfig | None = None) -> None:
self.config = config or DeepFMConfig()
self.params: dict[str, np.ndarray] = {}
self.field_dims_: tuple = ()
self.loss_history: list[float] = []
def _init_params(self, X_sparse: np.ndarray) -> None:
cfg = self.config
rng = np.random.default_rng(cfg.seed)
self.field_dims_, self._offsets = _field_offsets(X_sparse, cfg.field_dims)
total, F, k = sum(self.field_dims_), len(self.field_dims_), cfg.embedding_size
self.params = {"bias": np.zeros(1), "w": np.zeros(total), "V": rng.normal(0.0, 0.1, size=(total, k))}
if cfg.use_deep:
_mlp_init(self.params, "deep.", [F * k, *cfg.hidden_sizes, 1], rng)
self._n_deep = len(cfg.hidden_sizes) + 1
def _rows(self, X_sparse: np.ndarray) -> np.ndarray:
"""Per-field ids -> rows of the shared embedding table. (n, F) -> (n, F)."""
X_sparse = np.asarray(X_sparse, dtype=int)
if (X_sparse >= np.array(self.field_dims_)[None, :]).any() or X_sparse.min() < 0:
raise ValueError("X_sparse holds an id outside the field sizes the model was built with")
return X_sparse + self._offsets[None, :]
def _forward(self, X_sparse: np.ndarray):
cfg, p = self.config, self.params
idx = self._rows(X_sparse)
V = p["V"][idx] # (n, F, k)
logit = p["bias"][0] + p["w"][idx].sum(axis=1)
if cfg.use_fm:
logit = logit + fm_second_order(V)
acts = None
if cfg.use_deep:
acts = _mlp_forward(p, "deep.", V.reshape(len(V), -1), self._n_deep, last_linear=True)
logit = logit + acts[-1][:, 0]
return logit, (idx, V, acts)
def loss_and_grads(self, X_sparse: np.ndarray, y: np.ndarray) -> tuple[float, dict]:
"""Mean log-loss (plus the L2 penalty on the embeddings) and its gradients.
X_sparse: (n, F) ids. y: (n,) 0/1 labels. Returns (loss, {parameter name: gradient}).
"""
cfg, p = self.config, self.params
logit, (idx, V, acts) = self._forward(X_sparse)
loss, d = _bce(logit, np.asarray(y, dtype=float))
loss += 0.5 * cfg.l2 * float(np.sum(V**2)) / len(V)
grads = {"bias": np.array([d.sum()]), "w": np.zeros_like(p["w"]), "V": np.zeros_like(p["V"])}
np.add.at(grads["w"], idx, d[:, None])
dV = cfg.l2 * V / len(V)
if cfg.use_fm:
dV = dV + d[:, None, None] * (V.sum(axis=1, keepdims=True) - V)
if cfg.use_deep:
dV = dV + _mlp_backward(p, "deep.", acts, d[:, None], grads, last_linear=True).reshape(V.shape)
np.add.at(grads["V"], idx, dV)
return loss, grads
def fit(self, X_sparse: np.ndarray, y: np.ndarray) -> "DeepFM":
"""Train with mini-batch Adam. X_sparse: (n, F) one integer id per field. y: (n,) 0/1 labels."""
X_sparse = np.asarray(X_sparse, dtype=int)
self._init_params(X_sparse)
_adam_fit(self, (X_sparse,), np.asarray(y, dtype=float))
return self
def predict_proba(self, X_sparse: np.ndarray) -> np.ndarray:
"""Probability of a positive label. (n, F) -> (n,)."""
return _sigmoid(self._forward(X_sparse)[0])
def predict(self, X_sparse: np.ndarray) -> np.ndarray:
"""0/1 labels at probability 0.5. (n, F) -> (n,)."""
return (self._forward(X_sparse)[0] >= 0).astype(int)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 6, run with
python3 -m unittest -v
Practice
Call fm_second_order on an array of shape (1, 3, 2) holding the three vectors above and confirm it returns 2. Then fit DeepFM on the README data, where the click depends on the pair of ids and on neither id alone, with use_fm=False, with use_deep=False, and with both. Compare the accuracies.
Check on learning
- A logistic regression with a separate weight for every pair of ids could also model pairs. Why does the factorization machine generalise better on sparse data?
A way to think about it
Count how many rows inform one pair weight, and how many rows inform one latent vector. Then consider a pair that never occurred.
- In the README data the click depends on whether the sum of two ids is even. Why can the first-order weights not learn this at all?
A way to think about it
Fix one id and average the label over all values of the other. See whether any single id is associated with more clicks.
- The FM and the deep network share the same embeddings. What is gained by sharing, compared with giving each part its own table?
A way to think about it
Think about how many parameters each row updates, and about what the deep part receives at the start of training in each design.
- Why does the identity for the pairwise sum matter in practice, given that both forms give the same number?
A way to think about it
Compare the cost of each form as the number of fields grows from 3 to 300, for every row of every batch.