Overview
A user's past behaviour usually covers several interests, for example shoes and books. A simple model averages the whole history into one vector, which blurs those interests together. The Deep Interest Network builds a different user vector for every candidate item. A small network scores each past item against the candidate, and the history is summed with those scores as weights. When the candidate is a book, the book purchases dominate the sum and the shoes are mostly ignored. The model then predicts a click from this focused user vector together with the candidate itself.
A short history
Guorui Zhou and colleagues at Alibaba published the Deep Interest Network at KDD in 2018. Earlier click models averaged a user's whole behaviour history into one fixed vector, which blurred diverse interests together. DIN applies attention so that the history is summarised differently for each candidate item. The authors reported its use in Alibaba's display advertising system, and it started a line of history-aware ranking models.
How it works
- Look up an embedding for every history item and for the candidate, from one shared table. Padding slots are masked out.
- For each history item, form the vector and pass it through the attention MLP to get one score .
- Use the raw scores as weights (the default), or pass them through a softmax over the real history items when
attention_softmax=True. - Sum the history embeddings with those weights to get the user vector .
- Concatenate , the candidate embedding and any dense features, and run the final MLP and a sigmoid to get the click probability.
- Train every embedding and both MLPs with Adam on the binary cross-entropy loss.
Watch out for
- With the default raw scores the weights are unbounded, so a long history can produce a much larger user vector than a short one. That keeps the strength of an interest but makes the scale depend on history length.
- With the softmax option the weights always sum to 1, so a user with ten matching items looks the same as a user with one. The strength of the interest is lost.
- Items that appear rarely have poorly trained embeddings, so their attention scores are close to noise.
- This template is a small version of the method: one id per item, ReLU in place of the paper's Dice activation, and no mini-batch aware regularisation.
Use cases
When to use it
Click-through-rate prediction and ranking where users have varied interests and a behaviour history is available. If histories are short or uniform, plain sum or mean pooling does as well.
In industry
- E-commerce advertising
- Display ad ranking of the kind described in the original Alibaba paper: past clicks relevant to the candidate product get more weight.
- Video and music streaming
- Ranking the next item to show by attending to the parts of the watch or listen history that resemble the candidate.
- Marketplaces
- Ordering search and feed results using each shopper's recent views and purchases.
Choosing it: what must hold
- A logged behaviour sequence for each user, such as items clicked or bought.
- Users with varied interests, so that one averaged history vector loses information.
- Enough interaction data to learn item embeddings.
When to choose something else
| If | Use instead |
|---|---|
| Users have little or no history | DeepFM or Wide & Deep on profile and context features |
| The order and timing of the history matters strongly | A sequence model such as a GRU or a Transformer over the history |
| You need to pick candidates from millions of items first | A two-tower retrieval model, with DIN as the ranking stage |
Math foundations
Attention score
One number per history item that says how relevant it is to the candidate. The difference and the product are given explicitly so the small network does not have to learn them.
Candidate-dependent user vector
A weighted sum of the history. Because depends on the candidate, the same user gets a different vector for each item being scored. The mask removes padding.
Optional softmax weights
With
attention_softmax=Truethe scores are normalised to sum to 1 over the real items, and replaces in the sum above.Prediction
The final network reads the pooled history, the candidate and the dense features, and outputs the click probability.
Loss
Binary cross-entropy over the training rows. Its gradient flows back through the attention weights into the embeddings.
Symbols
- embedding of the j-th history item
- embedding of the candidate item
- attention score of history item j for this candidate
- mask: 1 for a real item, 0 for padding
- normalised attention weight
- the user vector for candidate c
- length of the history, including padding
- element-wise product
- optional dense features
- predicted click probability and true label
Worked by hand
A history of two items with embeddings and . For the current candidate the attention MLP gives scores and .
With raw scores the first item dominates nine to one. The softmax flattens that to about seven to three, and the weights sum to 1 regardless of how strong the scores were.
Visual example
Loading the example.
Try this
- Switch the candidate from a pair of shoes to a book and watch the weight move to the books in the history.
- Take every book out of the history, then score a book: the click probability falls.
- Change the weights to softmax and see them sum to 1 however strong the scores are.
Code sample
import numpy as np
from impl import DIN, PAD
from config import DINConfig
rng = np.random.default_rng(0)
n, n_items = 3000, 24 # an item's category is id % 4
liked = rng.integers(0, 4, size=n) # each user likes one category
history = liked[:, None] + 4 * rng.integers(0, 6, size=(n, 5))
history[:, 3:][rng.random((n, 2)) < 0.5] = PAD # histories of different lengths
candidate = rng.integers(0, n_items, size=n)
y = (candidate % 4 == liked).astype(int)
model = DIN(DINConfig(epochs=10)).fit(history, candidate, y)
print((model.predict(history, candidate) == y).mean())
print(model.attention_weights(history[:1], candidate[:1])) # one weight per history slot, 0 on paddingRead the implementation (189 lines)
"""DIN: Deep Interest Network, a click model that reads the user's history with attention on the candidate.
NumPy only, manual backpropagation. Instead of squeezing the whole behaviour history into one fixed vector,
DIN weighs each past item by how relevant it is to the item being scored:
h_j = embedding of history item j, c = embedding of the candidate item
w_j = attention MLP([h_j, c, h_j - c, h_j * c]) one scalar per history item
user = sum_j w_j h_j padding positions are masked out
logit = MLP([user, c, dense features])
"""
from __future__ import annotations
import numpy as np
try:
from .config import DINConfig
except ImportError: # run from the template's own folder
from config import DINConfig
PAD = -1 # id that marks an empty history slot
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))
class DIN:
"""Click-through-rate model over (behaviour history, candidate item, optional dense features)."""
def __init__(self, config: DINConfig | None = None) -> None:
self.config = config or DINConfig()
self.params: dict[str, np.ndarray] = {}
self.n_items_ = 0
self.loss_history: list[float] = []
def _init_params(self, n_items: int, n_dense: int) -> None:
cfg = self.config
rng = np.random.default_rng(cfg.seed)
k = cfg.embedding_size
self.n_items_, self._n_dense = n_items, n_dense
self.params = {"E": rng.normal(0.0, 1.0 / np.sqrt(k), size=(n_items, k))}
_mlp_init(self.params, "att.", [4 * k, *cfg.attention_sizes, 1], rng)
_mlp_init(self.params, "out.", [2 * k + n_dense, *cfg.hidden_sizes, 1], rng)
self._n_att, self._n_out = len(cfg.attention_sizes) + 1, len(cfg.hidden_sizes) + 1
def _inputs(self, history, candidate, X_dense):
history = np.asarray(history, dtype=int)
candidate = np.asarray(candidate, dtype=int)
X_dense = np.zeros((len(candidate), 0)) if X_dense is None else np.asarray(X_dense, dtype=float)
if history.ndim != 2 or len(history) != len(candidate):
raise ValueError("history must be (n, L) and candidate (n,)")
return history, candidate, X_dense
def _forward(self, history: np.ndarray, candidate: np.ndarray, X_dense: np.ndarray):
cfg, p = self.config, self.params
if max(history.max(initial=PAD), candidate.max(initial=0)) >= self.n_items_ or candidate.min(initial=0) < 0:
raise ValueError("an item id is outside the range the model was built with")
if X_dense.shape[1] != self._n_dense:
raise ValueError("X_dense does not have the number of columns the model was built with")
mask = (history != PAD).astype(float) # (n, L)
hist_idx = np.where(history == PAD, 0, history)
H = p["E"][hist_idx] * mask[:, :, None] # (n, L, k); padding rows are zero
c = p["E"][candidate] # (n, k)
C = np.broadcast_to(c[:, None, :], H.shape)
att = _mlp_forward(p, "att.", np.concatenate([H, C, H - C, H * C], axis=2), self._n_att, last_linear=True)
scores = att[-1][:, :, 0] # (n, L)
if cfg.attention_softmax:
e = np.exp(np.where(mask > 0, scores, -np.inf) - scores.max(axis=1, keepdims=True))
total = e.sum(axis=1, keepdims=True)
w = np.divide(e, total, out=np.zeros_like(e), where=total > 0)
else:
w = scores * mask
user = np.sum(w[:, :, None] * H, axis=1) # (n, k)
out = _mlp_forward(p, "out.", np.hstack([user, c, X_dense]), self._n_out, last_linear=True)
return out[-1][:, 0], (mask, hist_idx, H, c, att, w, out)
def attention_weights(self, history, candidate, X_dense=None) -> np.ndarray:
"""Weight given to each history slot when scoring the candidate. Returns (n, L); padding slots are 0."""
return self._forward(*self._inputs(history, candidate, X_dense))[1][5]
def loss_and_grads(self, history, candidate, X_dense, y) -> tuple[float, dict]:
"""Mean log-loss and its gradients.
history: (n, L) item ids, PAD (-1) for empty slots. candidate: (n,) item ids. X_dense: (n, d).
y: (n,) 0/1 labels.
"""
cfg, p, k = self.config, self.params, self.config.embedding_size
logit, (mask, hist_idx, H, c, att, w, out) = self._forward(history, candidate, X_dense)
loss, d = _bce(logit, np.asarray(y, dtype=float))
grads: dict[str, np.ndarray] = {}
dout_in = _mlp_backward(p, "out.", out, d[:, None], grads, last_linear=True)
duser, dc = dout_in[:, :k], dout_in[:, k:2 * k].copy()
dH = w[:, :, None] * duser[:, None, :]
dw = np.sum(H * duser[:, None, :], axis=2) # (n, L)
if cfg.attention_softmax:
dscores = w * (dw - np.sum(dw * w, axis=1, keepdims=True))
else:
dscores = dw * mask
da = _mlp_backward(p, "att.", att, dscores[:, :, None], grads, last_linear=True) # (n, L, 4k)
C = c[:, None, :]
dH = dH + da[:, :, :k] + da[:, :, 2 * k:3 * k] + da[:, :, 3 * k:] * C
dc += np.sum(da[:, :, k:2 * k] - da[:, :, 2 * k:3 * k] + da[:, :, 3 * k:] * H, axis=1)
grads["E"] = np.zeros_like(p["E"])
np.add.at(grads["E"], hist_idx, dH * mask[:, :, None])
np.add.at(grads["E"], candidate, dc)
return loss, grads
def fit(self, history, candidate, y, X_dense=None) -> "DIN":
"""Train with mini-batch Adam.
history: (n, L) ids of the items the user interacted with, PAD (-1) in unused slots.
candidate: (n,) id of the item being scored. y: (n,) 0/1 labels.
X_dense: optional (n, d) extra features (user profile, context) fed to the final MLP.
"""
history, candidate, X_dense = self._inputs(history, candidate, X_dense)
n_items = self.config.n_items or int(max(history.max(), candidate.max())) + 1
self._init_params(n_items, X_dense.shape[1])
_adam_fit(self, (history, candidate, X_dense), np.asarray(y, dtype=float))
return self
def predict_proba(self, history, candidate, X_dense=None) -> np.ndarray:
"""Probability of a click, (n,)."""
return _sigmoid(self._forward(*self._inputs(history, candidate, X_dense))[0])
def predict(self, history, candidate, X_dense=None) -> np.ndarray:
"""0/1 labels at probability 0.5, (n,)."""
return (self._forward(*self._inputs(history, candidate, X_dense))[0] >= 0).astype(int)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 6, run with
python3 -m unittest -v
Practice
Build the README data, where an item's category is its id modulo 4 and each user likes one category. Fit DIN, then call attention_weights for one user with two different candidates, one in the liked category and one outside it. Describe how the weights change, and check that padding slots get weight 0.
Check on learning
- Mean pooling gives every user one fixed vector. Why can that hurt a user whose history is half shoes and half books?
A way to think about it
Work out where the average of two distinct clusters of embeddings lies, and whether that point is close to either a shoe or a book candidate.
- The paper uses raw scores as weights and does not normalise them. What information would the softmax throw away?
A way to think about it
Compare a user with one relevant item to a user with twenty, under each scheme. Look at the length of the pooled vector.
- Why feed the attention network and when it already receives and ?
A way to think about it
A small MLP could compute these itself in principle. Think about how much capacity and data that would cost, compared with handing them over directly.
- If every user's history were a single item, would this model have any advantage over plain pooling?
A way to think about it
Write the weighted sum for one item. Consider what the attention score still does, and whether the final MLP could do the same job.