Sign in

Wide & Deep

Wide & Deep Learning

A binary classifier that adds a linear model on hand-built cross features to a neural network on learned embeddings, and trains the two together.

Overview

A recommender needs two abilities. It should remember specific facts, such as that users who installed one particular app often install another particular app. It should also generalise to combinations never seen before. A linear model on crossed features is good at the first: each cross gets its own weight. A neural network on embeddings is good at the second: similar categories get similar vectors, so what is learned for one carries over to its neighbours. Wide and Deep adds the two outputs into one score and trains them together, so each part covers what the other handles poorly.

A short history

Heng-Tze Cheng and colleagues at Google published Wide & Deep in 2016, describing its use for app recommendations in Google Play. Linear models on crossed features memorise specific combinations well but cannot generalise to unseen ones. Deep models on embeddings generalise but can over-generalise for niche items. Training the two parts together gave both properties, and the paper reported more app installs in online tests. It was released with TensorFlow and widely copied.

How it works

  1. Prepare the wide input: sparse features such as one-hot crosses of two categorical columns, built with cross_feature.
  2. The wide part is a single weighted sum of those features.
  3. The deep part looks up an embedding vector for each categorical id, concatenates them with any dense features, and passes the result through ReLU layers.
  4. Add the wide sum, the deep output and a bias, and apply a sigmoid to get the probability of the positive class.
  5. Compute the log loss. The same prediction error flows back into the wide weights, the deep layers and the embedding tables.
  6. Update everything jointly with Adam on shuffled mini-batches.

Watch out for

  • A cross of two high-cardinality columns creates a very wide, sparse input, and most of its weights see only a handful of rows. Cross only pairs you believe matter, and use l2_wide.
  • A category seen once or twice gets an embedding that is still close to its random start, so predictions for it are unreliable.
  • The template sizes each embedding table from the largest id seen in training. An unseen larger id at prediction time is out of range and fails.
  • The original method trains the wide part with a sparse-friendly optimiser and the deep part with another. This small version uses Adam for both.

Use cases

When to use it

Click or install prediction on categorical data where a few known feature interactions matter a great deal and the rest must be learned, as in app, ad and content recommendation.

In industry

App stores
App recommendation, as in the original Google Play system: the wide part recalls known pairs, the deep part suggests related apps.
Online advertising
Click prediction that keeps hand-built cross features from an older linear model while adding learned embeddings.
Retail and travel
Ranking products or listings where business rules and known strong combinations sit alongside learned similarity.

Choosing it: what must hold

  • Sparse categorical features and a large log of labelled interactions.
  • Knowledge of which feature crosses matter, since the wide part needs them written by hand.
  • A binary target such as install, click or purchase.

When to choose something else

IfUse instead
You do not want to design cross features by handDeepFM or Deep & Cross Network (DCN)
There are several targets to predict togetherMulti-gate Mixture-of-Experts (MMoE)
The dataset is a small tableLogistic regression or gradient boosted trees

Math foundations

  1. The wide part

    owide=wwide⊤xwideo_{\text{wide}} = \mathbf{w}_{\text{wide}}^\top \mathbf{x}_{\text{wide}}

    A linear model. With one-hot cross features, this simply reads off the weight of the one cross that is active, which is why it can memorise specific combinations.

  2. A cross feature

    ϕa,b(x)=1[c1=a]⋅1[c2=b],column=a⋅∣c2∣+b\phi_{a,b}(\mathbf{x}) = \mathbb{1}[c_1 = a] \cdot \mathbb{1}[c_2 = b], \qquad \text{column} = a \cdot \lvert c_2 \rvert + b

    The cross is 1 only when both categorical values occur together. The template's cross_feature puts that 1 in the column given by the second formula.

  3. The deep input

    a0=[ E1[c1],  …,  EF[cF],  xdense ]\mathbf{a}_0 = \big[\, E_1[c_1],\; \dots,\; E_F[c_F],\; \mathbf{x}_{\text{dense}} \,\big]

    Each categorical id selects a row of its embedding table, and the rows are concatenated with the dense features. The embeddings are learned, so related ids can end up close together.

  4. The deep part

    ai=relu⁡ ⁣(ai−1Wi+bi),odeep=alast⊤wout\mathbf{a}_i = \operatorname{relu}\!\left(\mathbf{a}_{i-1} W_i + \mathbf{b}_i\right), \qquad o_{\text{deep}} = \mathbf{a}_{\text{last}}^\top \mathbf{w}_{\text{out}}

    An ordinary multilayer network on the embedded input, ending in a single number.

  5. The joint prediction

    P(y=1∣x)=σ ⁣(owide+odeep+b)P(y = 1 \mid \mathbf{x}) = \sigma\!\left(o_{\text{wide}} + o_{\text{deep}} + b\right)

    The two parts are added before the sigmoid, so they share one output and are trained against one loss. This differs from training two models and averaging them.

  6. Loss and shared error

    L=−1n∑i=1n[yilog⁡pi+(1−yi)log⁡(1−pi)]+λ2∥wwide∥2,∂L∂oi=pi−yinL = -\frac{1}{n}\sum_{i=1}^{n}\big[y_i \log p_i + (1 - y_i)\log(1 - p_i)\big] + \frac{\lambda}{2}\lVert \mathbf{w}_{\text{wide}} \rVert^2, \qquad \frac{\partial L}{\partial o_i} = \frac{p_i - y_i}{n}

    The log loss with an optional penalty on the wide weights. Both parts receive the same error signal pi−yip_i - y_i, so each learns what the other has not yet explained.

Symbols

xwide\mathbf{x}_{\text{wide}}
wide features, usually sparse one-hot crosses
wwide\mathbf{w}_{\text{wide}}
weights of the wide part
cfc_f
id of categorical field f
∣c2∣\lvert c_2 \rvert
number of distinct values of the second field
EfE_f
embedding table of field f
xdense\mathbf{x}_{\text{dense}}
optional real-valued features for the deep part
ai,Wi,bi\mathbf{a}_i, W_i, \mathbf{b}_i
activations, weights and bias of deep layer i
wout,b\mathbf{w}_{\text{out}}, b
output weights of the deep part and the shared bias
owide,odeepo_{\text{wide}}, o_{\text{deep}}
contributions of the two parts to the logit
pi,yip_i, y_i
predicted probability and 0 or 1 label of row i
λ\lambda
L2 strength on the wide weights, l2_wide

Worked by hand

Two categorical fields with 3 and 4 distinct values. A row has ids c1=2c_1 = 2 and c2=1c_2 = 1. The wide weight of its active cross is 0.8, the deep part outputs −0.3-0.3 and the bias is 0.1.

cross column=2×4+1=9of 3×4=12\text{cross column} = 2 \times 4 + 1 = 9 \quad \text{of } 3 \times 4 = 12
owide=0.8o_{\text{wide}} = 0.8
logit=0.8+(−0.3)+0.1=0.6\text{logit} = 0.8 + (-0.3) + 0.1 = 0.6
p=σ(0.6)=11+e−0.6=0.6457p = \sigma(0.6) = \frac{1}{1 + e^{-0.6}} = 0.6457

The model predicts 0.65. The memorised cross pushes the score up, the deep part pulls it slightly down, and the final answer is their sum passed through the sigmoid.

Visual example

Loading the example.

Try this

  • Switch to the wide part only and click a pair with a dashed outline: its weight is still 0.
  • Switch to the deep part only and click the pair with the solid outline to see the exception smoothed away.
  • With both parts on, raise the L2 strength and watch the wide part lose its grip on the exception.

Code sample

import numpy as np
from impl import WideDeep, cross_feature
from config import WideDeepConfig

rng = np.random.default_rng(0)
cats = rng.integers(0, 6, size=(1000, 2))                       # two categorical fields with 6 values each
y = (cats[:, 0] % 2 == cats[:, 1] % 2).astype(float)            # a general rule the deep part can learn
y[(cats[:, 0] == 3) & (cats[:, 1] == 5)] = 0.0                  # one exception to memorise
wide = cross_feature(cats[:, 0], cats[:, 1], 6, 6)              # (1000, 36) one-hot cross-product

model = WideDeep(WideDeepConfig(epochs=30)).fit(wide, cats, y)
print(((model.predict_proba(wide, cats) > 0.5) == y).mean())    # training accuracy, 1.0
Read the implementation (172 lines)
"""Wide & Deep binary classifier with manual backpropagation and Adam.

NumPy only. For a row with wide features x_w (sparse, usually one-hot crosses), categorical ids c_1..c_F and
optional dense features x_d:

    wide   = x_w . wide_w
    a_0    = concat(emb0[c_1], ..., emb{F-1}[c_F], x_d)
    a_i    = relu(a_{i-1} W{i-1} + b{i-1})          for every hidden layer
    deep   = a_last . out_w
    P(y=1) = sigmoid(wide + deep + bias)
"""
from __future__ import annotations

import numpy as np

try:
    from .config import WideDeepConfig
except ImportError:  # run from the template's own folder
    from config import WideDeepConfig


class _Adam:
    """Adam optimizer over a dict of NumPy arrays; `step` updates the arrays in place."""

    def __init__(self, params: dict, lr: float, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8) -> None:
        self.params, self.lr, self.beta1, self.beta2, self.eps = params, lr, beta1, beta2, eps
        self.m = {k: np.zeros_like(v) for k, v in params.items()}
        self.v = {k: np.zeros_like(v) for k, v in params.items()}
        self.t = 0

    def step(self, grads: dict) -> None:
        """Apply one update. grads: same keys and shapes as the parameters."""
        self.t += 1
        for k, g in grads.items():
            self.m[k] = self.beta1 * self.m[k] + (1 - self.beta1) * g
            self.v[k] = self.beta2 * self.v[k] + (1 - self.beta2) * g * g
            m_hat = self.m[k] / (1 - self.beta1**self.t)
            v_hat = self.v[k] / (1 - self.beta2**self.t)
            self.params[k] -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)

def _sigmoid(z: np.ndarray) -> np.ndarray:
    e = np.exp(-np.abs(z))
    return np.where(z >= 0, 1.0 / (1.0 + e), e / (1.0 + e))


def cross_feature(a: np.ndarray, b: np.ndarray, card_a: int, card_b: int) -> np.ndarray:
    """One-hot cross-product of two categorical columns, for the wide part.

    a: ids in 0..card_a-1, shape (n,). b: ids in 0..card_b-1, shape (n,). Returns (n, card_a * card_b) with a
    single 1 per row, at column a * card_b + b.
    """
    a = np.asarray(a, dtype=int)
    b = np.asarray(b, dtype=int)
    out = np.zeros((len(a), card_a * card_b))
    out[np.arange(len(a)), a * card_b + b] = 1.0
    return out


class WideDeep:
    """Wide & Deep model. After `fit`: `params`, `cardinalities_`, `loss_history_` (mean loss per epoch)."""

    def __init__(self, config: WideDeepConfig | None = None) -> None:
        self.config = config or WideDeepConfig()
        self.params: dict[str, np.ndarray] = {}
        self.cardinalities_: tuple[int, ...] = ()
        self.loss_history_: list[float] = []
        self._n_layers = len(self.config.hidden_sizes)

    def initialize(self, wide_dim: int, cardinalities, dense_dim: int = 0) -> None:
        """Create the weights.

        wide_dim: number of wide features. cardinalities: number of distinct ids of each categorical field.
        dense_dim: number of dense features fed to the deep part (0 for none).
        """
        cfg = self.config
        rng = np.random.default_rng(cfg.seed)
        self.cardinalities_ = tuple(int(c) for c in cardinalities)
        self.params = {"wide_w": np.zeros(wide_dim), "bias": np.zeros(1)}
        for f, card in enumerate(self.cardinalities_):
            self.params[f"emb{f}"] = 0.1 * rng.normal(size=(card, cfg.embed_dim))
        sizes = [len(self.cardinalities_) * cfg.embed_dim + dense_dim, *[int(h) for h in cfg.hidden_sizes]]
        for i, (fan_in, fan_out) in enumerate(zip(sizes[:-1], sizes[1:])):
            self.params[f"W{i}"] = np.sqrt(2.0 / fan_in) * rng.normal(size=(fan_in, fan_out))
            self.params[f"b{i}"] = np.zeros(fan_out)
        self.params["out_w"] = np.sqrt(1.0 / sizes[-1]) * rng.normal(size=sizes[-1])

    def _forward(self, wide: np.ndarray, cats: np.ndarray, dense: np.ndarray | None) -> tuple[np.ndarray, list]:
        """Returns the logit (n,) and the deep activations [a_0, ..., a_last]."""
        p = self.params
        parts = [p[f"emb{f}"][cats[:, f]] for f in range(len(self.cardinalities_))]
        if dense is not None:
            parts.append(dense)
        acts = [np.concatenate(parts, axis=1)]
        for i in range(self._n_layers):
            acts.append(np.maximum(acts[-1] @ p[f"W{i}"] + p[f"b{i}"], 0.0))
        return wide @ p["wide_w"] + acts[-1] @ p["out_w"] + p["bias"][0], acts

    def loss_and_grads(self, wide: np.ndarray, cats: np.ndarray, y: np.ndarray, dense: np.ndarray | None = None) -> tuple[float, dict]:
        """Log loss on a batch and its gradient for every parameter.

        wide: (n, wide_dim). cats: integer ids, (n, F). y: 0/1 labels, (n,). dense: optional (n, dense_dim).
        """
        p = self.params
        cfg = self.config
        n = len(y)
        logit, acts = self._forward(wide, cats, dense)
        loss = np.mean(np.logaddexp(0.0, logit) - y * logit) + 0.5 * cfg.l2_wide * np.sum(p["wide_w"] ** 2)
        d_logit = (_sigmoid(logit) - y) / n
        grads = {
            "wide_w": wide.T @ d_logit + cfg.l2_wide * p["wide_w"],
            "bias": np.array([d_logit.sum()]),
            "out_w": acts[-1].T @ d_logit,
        }
        delta = np.outer(d_logit, p["out_w"])
        for i in reversed(range(self._n_layers)):
            delta = delta * (acts[i + 1] > 0)
            grads[f"W{i}"] = acts[i].T @ delta
            grads[f"b{i}"] = delta.sum(axis=0)
            delta = delta @ p[f"W{i}"].T
        # delta is now the gradient at the concatenated embeddings: scatter it back into the tables.
        e = cfg.embed_dim
        for f in range(len(self.cardinalities_)):
            table_grad = np.zeros_like(p[f"emb{f}"])
            np.add.at(table_grad, cats[:, f], delta[:, f * e : (f + 1) * e])
            grads[f"emb{f}"] = table_grad
        return float(loss), grads

    def fit(self, wide: np.ndarray, cats: np.ndarray, y: np.ndarray, dense: np.ndarray | None = None) -> "WideDeep":
        """Train both parts jointly with mini-batch Adam.

        wide: wide features, shape (n, wide_dim). cats: categorical ids starting at 0, shape (n, F).
        y: 0/1 labels, shape (n,). dense: optional real-valued features for the deep part, shape (n, dense_dim).
        """
        cfg = self.config
        wide = np.asarray(wide, dtype=float)
        cats = np.asarray(cats, dtype=int)
        y = np.asarray(y, dtype=float)
        dense = None if dense is None else np.asarray(dense, dtype=float)
        if wide.ndim != 2 or cats.ndim != 2 or not (len(wide) == len(cats) == len(y)):
            raise ValueError("wide must be (n, wide_dim), cats (n, F) and y (n,)")
        if not np.isin(y, (0.0, 1.0)).all():
            raise ValueError("y must hold 0/1 labels")
        self.initialize(wide.shape[1], cats.max(axis=0) + 1, 0 if dense is None else dense.shape[1])
        optimizer = _Adam(self.params, cfg.lr)
        rng = np.random.default_rng(cfg.seed + 1)
        self.loss_history_ = []
        n = len(y)
        for _ in range(cfg.epochs):
            order = rng.permutation(n)
            total = 0.0
            for start in range(0, n, cfg.batch_size):
                rows = order[start : start + cfg.batch_size]
                loss, grads = self.loss_and_grads(wide[rows], cats[rows], y[rows], None if dense is None else dense[rows])
                optimizer.step(grads)
                total += loss * len(rows)
            self.loss_history_.append(total / n)
        return self

    def predict_proba(self, wide: np.ndarray, cats: np.ndarray, dense: np.ndarray | None = None) -> np.ndarray:
        """Probability of the positive class. Same argument shapes as `fit`. Returns shape (n,)."""
        if not self.params:
            raise RuntimeError("call fit (or initialize) before predicting")
        dense = None if dense is None else np.asarray(dense, dtype=float)
        return _sigmoid(self._forward(np.asarray(wide, dtype=float), np.asarray(cats, dtype=int), dense)[0])

    def predict(self, wide: np.ndarray, cats: np.ndarray, dense: np.ndarray | None = None) -> np.ndarray:
        """0/1 predictions at threshold 0.5. Same argument shapes as `fit`. Returns shape (n,)."""
        return (self.predict_proba(wide, cats, dense) >= 0.5).astype(int)

    def wide_logit(self, wide: np.ndarray) -> np.ndarray:
        """Contribution of the wide part alone to the logit. wide: (n, wide_dim). Returns shape (n,)."""
        return np.asarray(wide, dtype=float) @ self.params["wide_w"]
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Generate two categorical columns and a label that is mostly a smooth function of the columns, but with one specific pair of values that is always positive. Build the wide input with cross_feature and fit WideDeep with the default WideDeepConfig. Use wide_logit to find which crosses got large weights. Then refit with a wide input of all zeros, so that only the deep part can learn, and compare predict_proba on the special pair.

Check on learning

  1. The deep part could in principle learn any interaction the wide part holds. Why add the wide part at all?
    A way to think about it

    Think of a rare exception that contradicts the general pattern. Ask how many examples an embedding network needs to carve out one exact pair, against a single dedicated weight.

  2. The two parts are added before the sigmoid and trained together. How does that differ from training each separately and averaging their probabilities?
    A way to think about it

    In joint training each part sees the error left by the other. Consider what the wide part needs to learn when the deep part already predicts most rows well.

  3. You cross two columns with 10000 values each. How many wide weights does that create, and what goes wrong?
    A way to think about it

    Multiply the cardinalities, then compare with the number of training rows. Most crosses never occur, and those that occur once are fitted to a single label.

  4. A new item id appears that was never in training. Which part of the model has anything useful to say about it, and under what conditions?
    A way to think about it

    Neither a cross weight nor an embedding exists for an unseen id. Think about what dense features or other fields of that item could still feed the deep part.