Electric Sheaves

Lecture 2 — Neural Networks and Approximation

Project connection. Project Step 2 asks you to wire a one-hidden-layer ReLU network from explicit matrices. Four hidden units build the nonlinear feature x1+x2|x_1|+|x_2|; two output logits and softmax turn it into a classifier with a diamond-shaped decision boundary.

Chapter overview. Lecture 1 described a language model as a map from contexts to probability distributions. We now replace an explicit matrix of probabilities by a parametrized function. We begin with binary logistic regression, because every calculation fits on one line, and then pass to softmax regression and neural networks. The final sections ask what such networks can represent, why depth can help, and what those representation theorems do—and do not—say about training a useful model.

0. The sigmoid function and logistic regression

We begin with a new type of model. We will connect this with language models (from the last lecture) later in this lecture.

A classification problem asks us to predict which of several categories an observation belongs to.

Let C\mathcal{C} be a finite set whose members are called classes or labels. In binary classification there are two possible classes, typically C={0,1}\mathcal{C}=\{0,1\}. Let Δ(C)\Delta(\mathcal{C}) be the probability simplex on C\mathcal{C}, i.e. the set of probability distributions on C\mathcal{C}.

The input space is a set XRd\mathcal{X}\subseteq\mathbb R^d whose elements are called feature vectors. Each of the dd standard coordinates of Rd\mathbb R^d is called a feature, so that a feature vector

x=(x1,,xd)Rd\mathbf{x}=(x_1,\ldots,x_d)^\top\in\mathbb R^d

has a value xix_i for the ii-th feature.

For a classification problem, we use the same notation as for a language model. Let ΘRk\Theta\subseteq\mathbb R^k be the parameter space. A probabilistic classifier for X\mathcal X and C\mathcal C is a function

P:Θ×XΔ(C),(θ,x)pθ(x):=P(θ,x),P:\Theta\times\mathcal X\longrightarrow\Delta(\mathcal C), \qquad (\theta,\mathbf{x})\longmapsto p_\theta(\,\cdot\mid\mathbf{x}):=P(\theta,\mathbf{x}),

that is differentiable in θ\theta for each fixed x\mathbf{x}. Fixing θ\theta gives a trained classifier P(θ,)P(\theta,\cdot). We write pθ(cx)p_\theta(c\mid\mathbf{x}) for the probability it assigns to class cc on input x\mathbf{x}.

In the binary classification case, we can give the output probability distribution pθp_\theta on {0,1}\{0,1\} as a single number y^[0,1]\widehat y\in[0,1]:

pθ(y=1x)=y^,pθ(y=0x)=1y^.p_\theta(y=1\mid\mathbf{x})=\widehat y, \qquad p_\theta(y=0\mid\mathbf{x})=1-\widehat y.

Both a classification model and a language model are instances of a more general conditional probabilistic model: something that maps an input to a probability distribution on possible outputs.

Analogously to the last lecture, we will discuss training and maximum likelihood in this new context. In the case of a training set, we need to train the model on feature vectors which are accompanied by the “correct” labels. For example, many pictures of cats labelled as cats and many other pictures labelled as non-cats.

For a classification model, the training set consists of pairs (x,c)X×C(\mathbf{x},c)\in\mathcal{X}\times\mathcal{C} called training samples. In the context of the training set, the feature vector x\mathbf{x} is called the training observation and cc is the gold label. The value cc is the supposed “correct answer,” recorded along with the observation (perhaps x\mathbf{x} is derived from an image, and the label cc was assigned by a human being who knows how to recognise cats well). The term comes from “gold standard.”

It will be convenient to have a function that turns an arbitrary real number into a probability. The first useful elementary example is the sigmoid.

Definition 0.1 (sigmoid and logit). The sigmoid, or logistic function, is

σ:R(0,1),σ(z)=ez1+ez=11+ez.\sigma:\mathbb R\longrightarrow(0,1), \qquad \sigma(z)= \frac{e^z}{1+e^z} = \frac{1}{1+e^{-z}}.

For p(0,1)p\in(0,1), its logit is

logit:(0,1)R,logit(p)=logp1p.\operatorname{logit}: (0,1) \longrightarrow \mathbb R, \qquad \operatorname{logit}(p)=\log\frac{p}{1-p}.

The two functions are inverses: logit(σ(z))=z\operatorname{logit}(\sigma(z))=z and σ(logit(p))=p\sigma(\operatorname{logit}(p))=p. Indeed,

σ(z)1σ(z)=1/(1+ez)ez/(1+ez)=ez,\frac{\sigma(z)}{1-\sigma(z)} = \frac{1/(1+e^{-z})}{e^{-z}/(1+e^{-z})} =e^z,

and taking logarithms gives the first identity. The second follows in the same way.

−4 −2 0 2 4 z 0 1/2 1 (0, 1/2) σ(z)
1/4 1/2 3/4 p 3 −3 (1/2, 0) (3/4, log 3) logit(p)
The sigmoid σ(z) (left) and its inverse, the logit (right).

Suppose an event has probability pp. Then the ratio p/(1p)p/(1-p) is called the odds of the event. A probability of 3/43/4 corresponds to odds 33. This is more commonly written 3:13:1 in gambling, which may be the more familiar form for “odds”. The logit of p=3/4p=3/4 is log3\log 3. Thus a logit is a log-odds ratio, which supposedly explains the terminology.

Now we introduce a simple binary classification model which we will use as a building block for a neural network.

Definition 0.2 (binary logistic regression). A binary logistic regression model is a binary classification model

P(θ,x)=pθ(x)P(\theta,\mathbf{x})=p_\theta(\,\cdot\mid\mathbf{x})

with parameter

θ=(w,b)Rd×R,\theta=(\mathbf{w},b)\in\mathbb R^d\times\mathbb R,

given by

pθ(y=1x)=σ(zθ(x))=:y^,pθ(y=0x)=1σ(zθ(x))=1y^,p_\theta(y=1\mid\mathbf{x})=\sigma(z_\theta(\mathbf{x})) =: \widehat y, \qquad p_\theta(y=0\mid\mathbf{x})=1-\sigma(z_\theta(\mathbf{x})) = 1 - \widehat y,

where

zθ(x)=wx+b.z_\theta(\mathbf{x})=\mathbf{w}^\top\mathbf{x}+b.

The entries of w\mathbf{w} are the weights, bb is the bias, and zθ(x)z_\theta(\mathbf{x}) is the logit (so named because it will be fed into a sigmoid).

Aside (why “regression”?). The adjective “regression” is historical. In statistics, regression refers to fitting a function to data. The name descended from Galton’s nineteenth-century studies of “regression toward the mean” in heredity. Logistic regression earns the name because it is linear regression of the log-odds.

A model produces a probability distribution. We typically want to turn the probability into a label prediction (a “yes” or “no”). One common rule is to predict 11 exactly when its probability is at least 1/21/2. Since σ(0)=1/2\sigma(0)=1/2 and σ\sigma is increasing, this is equivalent to

wx+b0.\mathbf{w}^\top\mathbf{x}+b\geq 0.

The map xwx+b\mathbf{x}\mapsto\mathbf{w}^\top\mathbf{x}+b is affine: it is a linear map plus a constant. Its zero set is an affine hyperplane, and we define this set to be the decision boundary:

{xRd:wx+b=0},\{\mathbf{x}\in\mathbb R^d:\mathbf{w}^\top\mathbf{x}+b=0\},

where the prediction switches from one label to the other. The equation above describes a translated hyperplane normal to w\mathbf{w}. As the parameters (w,b)(\mathbf{w},b) vary, the decision boundary can translate and rotate, but it is always a hyperplane. This flatness is the limitation that hidden layers will remove in Section 4.

ŷ > ½: predict 1 ŷ < ½: predict 0 w wᵀx + b = 0
The decision boundary in a plane of two features.

As a summary of binary logistic regression, here is a schematic:

features x ∈ ℝᵈ logit z ∈ ℝ probability ŷ ∈ (0, 1) prediction 1 or 0 affine map z = wᵀx + b sigmoid ŷ = σ(z) threshold 1 iff ŷ ≥ ½ θ = (w, b) fixed fixed
The binary logistic regression pipeline. The parameters θ affect only the affine map.

Example 0.3 (a tiny delay model). Think back to our example about predicting train delay. Suppose two standardized features are

x1=recent delay on the route,x2=amount of rain,x_1=\text{recent delay on the route}, \qquad x_2=\text{amount of rain},

and consider

z(x)=1.2x1+0.7x20.4.z(\mathbf{x})=1.2x_1+0.7x_2-0.4.

In other words, θ=(w,b)\theta=(\mathbf{w},b) with w=(1.2,0.7)\mathbf{w}=(1.2,\,0.7)^\top and b=0.4b=-0.4. For a journey with x=(0.5,1)\mathbf{x}=(0.5,1)^\top, the logit is

z(x)=1.2(0.5)+0.7(1)0.4=0.9.z(\mathbf{x})=1.2(0.5)+0.7(1)-0.4=0.9.

The estimated probability of a delay is therefore

y^=σ(0.9)0.711.\widehat y=\sigma(0.9)\approx 0.711.

The odds are e0.92.46e^{0.9}\approx2.46 (recall that the logit is log odds), so the model regards a delay as about 2.462.46 times as likely as no delay. The decision boundary is the line

1.2x1+0.7x20.4=0.1.2x_1+0.7x_2-0.4=0.
−1 1 1 2 −1 x₁ x₂ delay more likely (z > 0) on time more likely (z < 0) x = (0.5, 1) ŷ ≈ 0.711 1.2x₁ + 0.7x₂ − 0.4 = 0

ChatGPT helpfully points out: “This is a toy model, not a claim that two features adequately describe a railway.”

Now, how to train our model (choose a good θ\theta)? For a binary classification model, the training set consists of pairs called training samples

(x1,y1),,(xN,yN),xiRd,yi{0,1}.(\mathbf{x}_1,y_1),\ldots,(\mathbf{x}_N,y_N), \qquad \mathbf{x}_i\in\mathbb R^d,\quad y_i\in\{0,1\}.

Compare the following definition to the likelihood and average negative log likelihood of Lecture 1, Section 3: it is the same recipe, with the (context, next-token) pairs of a language model replaced by (feature vector, label) pairs.

Definition 0.4 (likelihood and cross-entropy loss). Consider a training set consisting of pairs (xi,yi)i=1N(\mathbf{x}_i,y_i)_{i=1}^N; here yiy_i is the gold label for observation xi\mathbf{x}_i. The likelihood of θΘ\theta \in \Theta for this training set is

L(θ):=i=1Npθ(yixi)=i:yi=1σ(zθ(xi))i:yi=0(1σ(zθ(xi))).L(\theta) := \prod_{i=1}^N p_\theta(y_i \mid \mathbf{x}_i) = \prod_{i\,:\,y_i =1} \sigma(z_\theta(\mathbf{x}_i)) \prod_{i\,:\,y_i=0} \bigl(1-\sigma(z_{\theta}(\mathbf{x}_i))\bigr).

We wish to think of this as a function of θ\theta, with the training set fixed:

L:Θ[0,1].L : \Theta \rightarrow [0,1].

The average negative log likelihood (also cross-entropy loss or log loss or cost; in the case of a training set specifically, also the empirical loss or training loss; in the case of binary regression specifically the binary loss; depending who you are talking to, hair loss or memory loss; in terms of what you’d rather be doing, caber toss) is

L(θ):=1NlogL(θ)=1Ni=1Nlogpθ(yixi).\mathcal{L}(\theta) := - \frac{1}{N} \log L(\theta) = - \frac{1}{N} \sum_{i=1}^N \log p_\theta(y_i \mid \mathbf{x}_i).

The individual terms

(θ;xi,yi):=logpθ(yixi)\ell(\theta;\mathbf{x}_i,y_i) :=-\log p_\theta(y_i\mid\mathbf{x}_i)

are called the pair-level log loss or log loss for the pair.

Minimizing L\mathcal L is the same as maximizing the likelihood L(θ)=i=1Npθ(yixi)L(\theta)=\prod_{i=1}^N p_\theta(y_i\mid\mathbf{x}_i). A maximum likelihood estimator, typically denoted θ^\widehat\theta, is a choice of minimizer of L\mathcal L, i.e. an input θ\theta at which L(θ)\mathcal L(\theta) attains its minimum (equivalently, at which L(θ)L(\theta) attains its maximum). There may be more than one, or there may be none.

Let us apply this to the binary classification model. From its definition, our model with parameter θ=(w,b)\theta=(\mathbf{w},b) returns a probability typically denoted

y^:=σ(wx+b).\widehat y:=\sigma(\mathbf{w}^\top\mathbf{x}+b).

This y^\widehat y is a compact way to describe the probability distribution, since

pθ(yx)={y^,y=1,1y^,y=0  =  y^y(1y^)1yp_\theta(y\mid\mathbf{x}) = \begin{cases} \widehat y,&y=1,\\ 1-\widehat y,&y=0 \end{cases} \;=\; \widehat y^{\,y}(1-\widehat y)^{1-y}

(a Bernoulli distribution with parameter y^\widehat y).

Therefore the log loss for an individual training pair (x,y)(\mathbf{x},y) is

(θ;x,y)=log(y^y(1y^)1y)=[ylogy^+(1y)log(1y^)].\ell(\theta;\mathbf{x},y) =-\log\left(\widehat y^{\,y}(1-\widehat y)^{1-y}\right) =-\left[ y\log\widehat y+(1-y)\log(1-\widehat y) \right].

When y=1y=1, the second term vanishes and =logy^\ell=-\log\widehat y. When y=0y=0, the first term vanishes and =log(1y^)\ell=-\log(1-\widehat y). We use the convention 0log0=00\log0=0 in formulas of this kind.

Notationally, y^\widehat y is typically used for a model prediction (here, the predicted probability of label 11), and y,yiCy, y_i \in \mathcal C for gold labels. Training involves comparing these two, and loss is a measure of how badly the model predicted reality.

1/4 1/2 3/4 1 ŷ = 0.711 0 1 2 3 −log ŷ (delay occurs, y = 1) −log(1 − ŷ) (on time, y = 0) ℓ ≈ 0.341 ℓ ≈ 1.241
The two branches of the binary cross-entropy loss ℓ as a function of the predicted probability ŷ of a delay. If a delay occurs (y = 1) the loss is the purple line; if it does not, the green one. The marked points are the two outcomes of Example 0.5, both at the prediction ŷ ≈ 0.711 of Example 0.3.

Example 0.5 (the loss of one prediction). For the journey in Example 0.3, the model regarded a delay as about 2.462.46 times as likely as no delay. In other words, the model predicts a delay is most probable. If a delay actually occurs, then

=log(0.711)0.341.\ell=-\log(0.711)\approx0.341.

If the train is instead on time, the same prediction incurs

=log(10.711)1.241.\ell=-\log(1-0.711)\approx1.241.

In short: correct predictions correspond to smaller losses. Falsely assigning a small probability pθ(yixi)p_\theta(y_i | \mathbf{x}_i) to the gold label yiy_i incurs a large loss. In particular, the loss diverges as the probability assigned to the observed label tends to zero.


1. Gradient descent for logistic regression

The definition of the maximum likelihood estimator θ^ΘRk\widehat\theta \in \Theta \subseteq \mathbb R^k (Definition 0.4) tells us what we want, but not how to find it. For a differentiable function F:RkRF:\mathbb R^k\to\mathbb R, its gradient at θ\theta is the vector of partial derivatives

F(θ)=(Fθ1(θ)Fθk(θ)).\nabla F(\theta) = \begin{pmatrix} \frac{\partial F}{\partial\theta_1}(\theta)\\ \vdots\\ \frac{\partial F}{\partial\theta_k}(\theta) \end{pmatrix}.

The directional derivative in direction vRkv \in \mathbb R^k is

ddtF(θ+tv)t=0=F(θ)v.\left.\frac{d}{dt}F(\theta+tv)\right|_{t=0} = \nabla F(\theta)^\top v.

Proposition 1.1 (direction of steepest descent). Let F:RkRF:\mathbb R^k\to\mathbb R be differentiable at θ\theta, with F(θ)0\nabla F(\theta)\neq0. Among all unit vectors vRkv\in\mathbb R^k, the directional derivative F(θ)v\nabla F(\theta)^\top v is smallest precisely when

v=F(θ)F(θ).v=-\frac{\nabla F(\theta)}{\|\nabla F(\theta)\|}.

Thus F(θ)-\nabla F(\theta) is the direction of steepest infinitesimal decrease.

Proof

Recall a classical fact from linear algebra, the Cauchy–Schwarz inequality:

For all u,vRku,v\in\mathbb R^k,

uvuv,|u^\top v|\le\|u\|\,\|v\|,

with equality if and only if uu and vv are linearly dependent.

Apply this with u=F(θ)u=\nabla F(\theta). For any unit vector vv,

F(θ)v    F(θ)v    F(θ),\nabla F(\theta)^\top v \;\geq\; -\left|\nabla F(\theta)^\top v\right| \;\geq\; -\|\nabla F(\theta)\|,

and by the equality case of Cauchy–Schwarz, the lower bound F(θ)-\|\nabla F(\theta)\| is attained only when vv is a scalar multiple of F(θ)\nabla F(\theta) — for a unit vector, only when v=±F(θ)/F(θ)v=\pm \nabla F(\theta)/\|\nabla F(\theta)\|. Trying both sign cases, we find that among unit vectors vv, the directional derivative is smallest when vv points opposite the gradient. \square

For one logistic-regression training sample (x,y)(\mathbf{x},y), we consider the log loss (θ):=(θ;x,y)\ell(\theta) := \ell(\theta; \mathbf{x}, y) of our model pθ(yx)p_\theta(y\mid\mathbf{x}) as a function of θ=(w,b)\theta = (\mathbf{w}, b). Recall that our goal is to choose θ\theta to result in small loss. The method of gradient descent will be defined formally below, but in brief, the idea is this. We will compute the gradient of \ell at the position θ\theta, and use the result to estimate an improved θ\theta by taking a step in the direction of decrease of loss. In equations:

θnew=θη(θ),\theta_{\text{new}} = \theta-\eta\,\nabla\ell(\theta),

where η>0\eta>0 is a small fixed number called the learning rate.

Picture the graph of a function FF of two variables as a landscape over the (θ1,θ2)(\theta_1,\theta_2)-plane. At any point, the negative gradient F(θ)-\nabla F(\theta) points steepest downhill. Gradient descent repeatedly takes a small step in that downhill direction, recomputing the direction after every step. The two pictures below show the same descent. In the contour picture, each step crosses the level curves at right angles, heading for lower and lower values of FF.

θ(0) −η∇F(θ(0)) minimum level curves of F
θ(0) minimum graph of F
Gradient descent on F(θ) = θ₁² + 3θ₂² with η = 0.13.

Definition 1.2 (gradient descent). Let F:RkRF:\mathbb R^k\to\mathbb R be differentiable, k1k \ge 1. Let ηR>0\eta \in \mathbb R_{>0}, which we call the learning rate. We write θ(t)Rk\theta^{(t)} \in \mathbb R^k where (t)(t) are indices, not exponents. Let θ(0)Rk\theta^{(0)} \in \mathbb R^k, which we call the initial vector. Define a sequence θ(t)\theta^{(t)} for t0t \ge 0 by the recurrence

θ(t+1):=θ(t)ηF(θ(t)),t0.\theta^{(t+1)} := \theta^{(t)}-\eta\nabla F(\theta^{(t)}), \quad t \ge 0.

We call the process of computing θ(t)\theta^{(t)}, as an algorithm, gradient descent.

For logistic regression we take F=LF=\mathcal L, the average cross-entropy loss, as a function on Θ=Rk\Theta = \mathbb R^k; here k=d+1k=d+1, viewing θ=(w,b)Rd×R\theta=(\mathbf{w},b)\in\mathbb R^d\times\mathbb R as a single vector.

We now demonstrate one step of gradient descent explicitly for logistic regression. Let us assume we have a single training sample (x,y)(\mathbf{x},y). The method of gradient descent views the log loss L=\mathcal{L}= \ell as a function of θ\theta, for our fixed training sample. So x\mathbf{x} and yy are constants, while θ=(w,b)\theta = (\mathbf{w},b) are the variables. Recall that we write

z=wx+bz=\mathbf{w}^\top\mathbf{x}+b

for the logit and y^=σ(z)\widehat y = \sigma(z) for the probability, as in Section 0, both functions of θ\theta. One step of gradient descent is

θnew=θη(θ).\theta_{\text{new}} = \theta-\eta\,\nabla\ell(\theta).

Proposition 1.3 (gradient of the log loss). In this setup,

w=(y^y)x,b=y^y,i.e.(θ)=(y^y)(x1).\boxed{ \nabla_{\mathbf{w}}\ell=(\widehat y-y)\,\mathbf{x}, \quad \frac{\partial\ell}{\partial b}=\widehat y-y, \quad\text{i.e.}\quad \nabla\ell(\theta) = (\widehat y-y) \begin{pmatrix}\mathbf{x}\\1\end{pmatrix}. }
Proof

Recall from Definition 0.4 that \ell is the log loss of our training sample,

(θ)=logpθ(yx)=[ylogy^+(1y)log(1y^)],\ell(\theta) = -\log p_\theta(y\mid\mathbf{x}) = -\left[y\log\widehat y+(1-y)\log(1-\widehat y)\right],

where y^=σ(wx+b)\widehat y=\sigma(\mathbf{w}^\top\mathbf{x}+b) is the probability the model assigns to the label 11.

We wish to compute the vector

(θ)=(w1,,wd,b).\nabla\ell(\theta) = \left( \frac{\partial\ell}{\partial w_1},\, \ldots,\, \frac{\partial\ell}{\partial w_d},\, \frac{\partial\ell}{\partial b} \right)^\top.

The loss depends on θ\theta only through the logit zz, so the chain rule expresses every one of these partial derivatives in terms of the single scalar /z\partial\ell/\partial z:

wj=zzwj,b=zzb.\frac{\partial\ell}{\partial w_j} = \frac{\partial\ell}{\partial z}\, \frac{\partial z}{\partial w_j}, \qquad \frac{\partial\ell}{\partial b} = \frac{\partial\ell}{\partial z}\, \frac{\partial z}{\partial b}.

From z=w1x1++wdxd+bz=w_1x_1+\cdots+w_dx_d+b we read off z/wj=xj\partial z/\partial w_j=x_j and z/b=1\partial z/\partial b=1, so

(θ)=z(x1,,xd,1)=z(x1).\nabla\ell(\theta) = \frac{\partial\ell}{\partial z} \,(x_1,\ldots,x_d,1)^\top = \frac{\partial\ell}{\partial z} \begin{pmatrix}\mathbf{x}\\1\end{pmatrix}.

It remains to compute the scalar /z\partial\ell/\partial z. The loss depends on zz through the probability y^=σ(z)\widehat y=\sigma(z), so we apply the chain rule once more:

z=y^dy^dz.\frac{\partial\ell}{\partial z} = \frac{\partial\ell}{\partial \widehat y}\, \frac{d\widehat y}{dz}.

Differentiating the binary cross-entropy =[ylogy^+(1y)log(1y^)]\ell = -\left[y\log\widehat y+(1-y)\log(1-\widehat y)\right] with respect to y^\widehat y gives

y^=yy^+1y1y^,\frac{\partial\ell}{\partial \widehat y} = -\frac{y}{\widehat y}+\frac{1-y}{1-\widehat y},

and the sigmoid has the pleasant derivative

dy^dz=dσdz(z)=ez(1+ez)2=σ(z)(1σ(z))=y^(1y^).\frac{d\widehat y}{dz} = \frac{d\sigma}{dz}(z) = \frac{e^{-z}}{(1+e^{-z})^2} = \sigma(z)(1-\sigma(z)) = \widehat y(1-\widehat y).

Multiplying the two,

z=(yy^+1y1y^)y^(1y^)=y(1y^)+(1y)y^=y^y.\begin{aligned} \frac{\partial\ell}{\partial z} &= \left( -\frac{y}{\widehat y}+\frac{1-y}{1-\widehat y} \right)\widehat y(1-\widehat y)\\ &=-y(1-\widehat y)+(1-y)\widehat y\\ &=\widehat y-y. \end{aligned}

Assembling the pieces gives the boxed formula. \square

Let us pause to interpret our computation. Recall that y^\widehat y is the predicted probability of our model, as a function of θ\theta. And yy is the gold label for our training sample (a constant). The factor y^y\widehat y-y is called the prediction error. If y=1y=1 and the model assigns too small a probability y^\widehat y, then y^y<0\widehat y-y<0: the negative-gradient update increases the logit. If the target is 00, then y^y>0\widehat y-y>0: the update decreases it.

Now suppose we have a larger training set (xi,yi)i=1N(\mathbf{x}_i, y_i)_{i=1}^N. Let XRN×dX\in\mathbb R^{N\times d} have row xi\mathbf{x}_i^\top, and let

y^i=σ(wxi+b).\widehat y_i=\sigma(\mathbf{w}^\top\mathbf{x}_i+b).

If y^=(y^1,,y^N)\widehat{\mathbf{y}}=(\widehat y_1,\ldots,\widehat y_N)^\top and y=(y1,,yN)\mathbf{y}=(y_1,\ldots,y_N)^\top are the vectors of probabilities and gold labels, and 1=(1,,1)RN\mathbf1=(1,\ldots,1)^\top\in\mathbb R^N denotes the all-ones vector, then

wL=1NX(y^y)Lb=1N1(y^y)\nabla_{\mathbf{w}}\mathcal L = \frac1N X^\top(\widehat{\mathbf{y}}-\mathbf{y}) \qquad \frac{\partial\mathcal L}{\partial b} = \frac1N\mathbf1^\top(\widehat{\mathbf{y}}-\mathbf{y})

Writing this out in matrix form, with the two blocks stacked into a single vector,

L(θ)=1N(x11x21xN1x12x22xN2x1dx2dxNd111)(y^1y1y^2y2y^NyN),\nabla\mathcal{L}(\theta) = \frac{1}{N} \begin{pmatrix} x_{11} & x_{21} & \cdots & x_{N1}\\ x_{12} & x_{22} & \cdots & x_{N2}\\ \vdots & \vdots & & \vdots\\ x_{1d} & x_{2d} & \cdots & x_{Nd}\\ 1 & 1 & \cdots & 1 \end{pmatrix} \begin{pmatrix} \widehat y_1 - y_1\\ \widehat y_2 - y_2\\ \vdots\\ \widehat y_N - y_N \end{pmatrix},

where xijx_{ij} denotes the jjth coordinate of xi\mathbf{x}_i, so that the first dd rows of the matrix form XX^\top and the final row of ones collects the bias derivatives.

This is the same calculation for every observation, collected into two matrix operations. The choice of transposes is simply further evidence that machine learning has a tendency to strange conventions. As before, the vector y^y\widehat{\mathbf{y}} - \mathbf{y} is the prediction error.

Another way to present these formulas is as an average. The log loss L\mathcal L is an average of the per-sample log losses (θ;xi,yi)\ell(\theta;\mathbf{x}_i,y_i), and differentiation is linear, so the gradient of the log loss is the average of the per-sample gradients:

L(θ)=1Ni=1N(θ;xi,yi)=1Ni=1N(y^iyi)(xi1).\nabla\mathcal L(\theta) = \frac1N\sum_{i=1}^N\nabla\ell(\theta;\mathbf{x}_i,y_i) = \frac1N\sum_{i=1}^N(\widehat y_i-y_i) \begin{pmatrix}\mathbf{x}_i\\1\end{pmatrix}.

A gradient descent step

θ(t+1):=θ(t)ηL(θ(t)),t0,\theta^{(t+1)} := \theta^{(t)}-\eta\nabla \mathcal{L}(\theta^{(t)}), \quad t \ge 0,

that uses this average over the whole training set (all NN samples) is called a full-batch step. The training set, used all at once in this way, is called the batch.

One run of gradient descent on the full training set is called an epoch of training. An alternative way to perform an epoch is minibatch, which averages over a small subset of the training set at each step, because for large training sets the full batch is too expensive to revisit at every training step. Note that different batch sizes do result in different gradient descent paths, hence different training outcomes.

The gradient descent algorithm for binary logistic regression becomes the following.

Algorithm 1.4 (gradient descent for logistic regression).

Input: data {(xi,yi)}i=1N\{(\mathbf{x}_i,y_i)\}_{i=1}^N, assembled into the matrix XRN×dX\in\mathbb R^{N\times d} whose iith row is xi\mathbf{x}_i^\top and the label vector y=(y1,,yN)\mathbf{y}=(y_1,\ldots,y_N)^\top; learning rate η>0\eta>0; number of steps TT; and initial weights θ(0)=(w(0)\theta^{(0)} = (\mathbf{w}^{(0)}, b(0))b^{(0)}).

For t=0,1,,T1t=0,1,\ldots,T-1:

  1. Compute the logits and probabilities of all samples at once:

    z(t)=Xw(t)+b(t)1,y^(t)=σ(z(t)),\mathbf{z}^{(t)}=X\mathbf{w}^{(t)}+b^{(t)}\mathbf1, \qquad \widehat{\mathbf{y}}^{(t)}=\sigma\bigl(\mathbf{z}^{(t)}\bigr),

    where σ\sigma is applied to each coordinate separately.

  2. Compute the two blocks L(θ(t))=(wL(θ(t)),bL(θ(t)))\nabla\mathcal L(\theta^{(t)})=\bigl(\nabla_{\mathbf{w}}\mathcal L(\theta^{(t)}),\,\nabla_{b}\mathcal L(\theta^{(t)})\bigr) of the gradient:

    wL(θ(t))=1NX(y^(t)y),bL(θ(t))=1N1(y^(t)y).\nabla_{\mathbf{w}}\mathcal L(\theta^{(t)})=\frac1NX^\top\bigl(\widehat{\mathbf{y}}^{(t)}-\mathbf{y}\bigr), \qquad \nabla_{b}\mathcal L(\theta^{(t)})=\frac1N\mathbf1^\top\bigl(\widehat{\mathbf{y}}^{(t)}-\mathbf{y}\bigr).
  3. Update:

    w(t+1)=w(t)ηwL(θ(t)),b(t+1)=b(t)ηbL(θ(t)).\mathbf{w}^{(t+1)}=\mathbf{w}^{(t)}-\eta\,\nabla_{\mathbf{w}}\mathcal L(\theta^{(t)}), \qquad b^{(t+1)}=b^{(t)}-\eta\,\nabla_{b}\mathcal L(\theta^{(t)}).

Output: θ(T)=(w(T),b(T))\theta^{(T)}=(\mathbf{w}^{(T)},b^{(T)}).

Example 1.5 (one complete gradient step). Take the two one-dimensional training samples

(x1,y1)=(1,0),(x2,y2)=(1,1),(x_1,y_1)=(-1,0), \qquad (x_2,y_2)=(1,1),

so that

X=(11),y=(01),X=\begin{pmatrix}-1\\1\end{pmatrix}, \qquad \mathbf{y}=\begin{pmatrix}0\\1\end{pmatrix},

and initialize θ(0)=(w(0),b(0))=(0,0)\theta^{(0)} = (w^{(0)},b^{(0)}) =(0,0). Both logits are 00, so both probabilities are 1/21/2: in step 1 of Algorithm 1.4,

z(0)=(00),y^(0)=(1/21/2).\mathbf{z}^{(0)}=\begin{pmatrix}0\\0\end{pmatrix}, \qquad \widehat{\mathbf{y}}^{(0)}=\begin{pmatrix}1/2\\1/2\end{pmatrix}.

Each sample therefore contributes log loss log(1/2)=log2-\log(1/2)=\log2, and the average loss at initialization is

L(θ(0))=log20.693.\mathcal L\bigl(\theta^{(0)}\bigr)=\log2\approx0.693.

The vector of prediction errors is

y^(0)y=(1/21/2),\widehat{\mathbf{y}}^{(0)}-\mathbf{y}=\begin{pmatrix}1/2\\-1/2\end{pmatrix},

so step 2 gives the two coordinates L(θ(0))=(wL(θ(0)),bL(θ(0)))\nabla\mathcal L(\theta^{(0)})=\bigl(\nabla_{w}\mathcal L(\theta^{(0)}),\,\nabla_{b}\mathcal L(\theta^{(0)})\bigr) of the full-batch gradient:

wL(θ(0))=12X(y^(0)y)=12(11)(1/21/2)=12,bL(θ(0))=121(y^(0)y)=12(11)(1/21/2)=0.\begin{aligned} \nabla_{w}\mathcal L(\theta^{(0)}) &= \frac12X^\top\bigl(\widehat{\mathbf{y}}^{(0)}-\mathbf{y}\bigr) = \frac12 \begin{pmatrix}-1&1\end{pmatrix} \begin{pmatrix}1/2\\-1/2\end{pmatrix} =-\frac12,\\ \nabla_{b}\mathcal L(\theta^{(0)}) &= \frac12\mathbf1^\top\bigl(\widehat{\mathbf{y}}^{(0)}-\mathbf{y}\bigr) = \frac12 \begin{pmatrix}1&1\end{pmatrix} \begin{pmatrix}1/2\\-1/2\end{pmatrix} =0. \end{aligned}

With learning rate η=1\eta=1, the update of step 3 gives

w(1)=12,b(1)=0.w^{(1)}=\frac12, \qquad b^{(1)}=0.

Consider the probability the updated model assigns to the gold label of each sample. On the second sample, the gold label is y2=1y_2=1, which receives probability

pθ(1)(y=1x2)=σ ⁣(w(1)x2+b(1))=σ(1/2)0.622.p_{\theta^{(1)}}(y=1\mid x_2) =\sigma\!\left(w^{(1)}x_2+b^{(1)}\right) =\sigma(1/2)\approx0.622.

On the first sample, the gold label is y1=0y_1=0, which receives probability

pθ(1)(y=0x1)=1σ ⁣(w(1)x1+b(1))=1σ(1/2)=σ(1/2)0.622p_{\theta^{(1)}}(y=0\mid x_1) =1-\sigma\!\left(w^{(1)}x_1+b^{(1)}\right) =1-\sigma(-1/2) =\sigma(1/2)\approx0.622

as well.

The single gradient step has reduced the average loss on this training set: it has fallen from log20.693\log2\approx0.693 to

log(0.622)0.474.-\log(0.622)\approx0.474.

Now we turn to asking whether gradient descent is well-behaved. If the function we are minimizing is convex, every local minimum is a global minimum, so we can hope that gradient descent will get us to a global minimum. Gradient descent is nice in this way in the case of logistic regression.

Definition 1.6 (convex function). A function F:RkRF:\mathbb R^k\to\mathbb R is convex if for all θ,θRk\theta,\theta'\in\mathbb R^k and all t[0,1]t\in[0,1],

F((1t)θ+tθ)    (1t)F(θ)+tF(θ).F\bigl((1-t)\theta+t\theta'\bigr) \;\leq\; (1-t)F(\theta)+tF(\theta').

Geometrically: the chord joining any two points of the graph lies on or above the graph. A convex function has no separate valleys for gradient descent to get trapped in.

convex not convex θ θ′ θ θ′ chord graph above chord
Convexity is the chord test. Left: for a convex function, any chord joining any two points of the graph (purple) lies on or above the graph. Right: a non-convex function fails the test for at least one chord.

Example 1.7 (the one-dimensional picture). Before we begin, we record a useful equivalent form for the loss, written in terms of the logit z=wx+bz=\mathbf{w}^\top\mathbf{x}+b rather than the probability. The model assigns probability

y^=σ(z)=ez1+ez\widehat y=\sigma(z)=\frac{e^z}{1+e^z}

to the outcome y=1y=1, and hence probability 1y^=1/(1+ez)1-\widehat y=1/(1+e^z) to the outcome y=0y=0. Taking logarithms,

logy^=zlog(1+ez),log(1y^)=log(1+ez).\log \widehat y = z-\log(1+e^z), \qquad \log(1-\widehat y) = -\log(1+e^z).

Substituting these into the log loss (θ;x,y)=ylogy^(1y)log(1y^)\ell(\theta;\mathbf{x},y)=-y\log\widehat y-(1-y)\log(1-\widehat y) gives

(θ;x,y)=y(zlog(1+ez))(1y)(log(1+ez))=log(1+ez)yz.\begin{aligned} \ell(\theta;\mathbf{x},y) &= -y\bigl(z-\log(1+e^z)\bigr)-(1-y)\bigl(-\log(1+e^z)\bigr)\\ &= \log(1+e^z)-yz. \end{aligned}

The function zlog(1+ez)z\mapsto\log(1+e^z) is sometimes called softplus. This softplus form of the loss makes the computation in the next example quick, and Exercise 3 uses it to prove that the loss is convex; its multiclass analog, log-sum-exp, appears in Section 3.

Now, in the case of one-dimensional feature vectors, where we freeze b=0b=0, we can draw a graph of the loss we are minimizing. The only parameter is θ=w\theta = w. For the two-point dataset of Example 1.5 the loss works out to L(w)=log(1+ew)\mathcal L(w)=\log(1+e^{-w}). This follows from the softplus form above, where the sample (1,0)(-1,0) contributes log(1+ew)\log(1+e^{-w}) and the sample (1,1)(1,1) contributes log(1+ew)w\log(1+e^{w})-w, which is the same number. This function is convex, but strictly decreasing, with infimum 00 that is never attained. If we instead use the three samples (1,0)(-1,0), (1,1)(1,1), (1,0)(1,0), the loss becomes a convex bowl with a unique minimizer at w=log2w=\log 2.

0 2 4 w 1 2 0 L(w) samples (−1, 0), (1, 1) samples (−1, 0), (1, 1), (1, 0) log 2
The cross-entropy loss L(w) for one-dimensional logistic regression with b = 0. The curves are labelled with the training samples that produced them.

Notice that our three-sample set of training data has a contradiction: different gold labels are assigned to the same feature vector. But real world data is like this! (A caution for later: the bowl in this picture depends on our having frozen b=0b=0. We return to this dataset after Theorem 1.11.)

How do we check that a function is convex? For a twice-differentiable function FF of one variable, convexity is equivalent to F0F''\geq0 everywhere: the slope never decreases. In mm variables, the role of the second derivative is played by a matrix.

Definition 1.8 (Hessian). Let F:RkRF:\mathbb R^k\to\mathbb R be twice differentiable. The Hessian of FF at θ\theta is the k×kk\times k matrix of second partial derivatives

2F(θ)=(2Fθiθj(θ))1i,jk.\nabla^2F(\theta) = \left( \frac{\partial^2F}{\partial\theta_i\,\partial\theta_j}(\theta) \right)_{1\leq i,j\leq k}.

Theorem 1.9 (second-order test for convexity). Let F:RkRF:\mathbb R^k\to\mathbb R be twice continuously differentiable. Then FF is convex if and only if the Hessian is positive semidefinite at every point, i.e.

u2F(θ)u0for all u,θRk.\mathbf{u}^\top\nabla^2F(\theta)\,\mathbf{u}\geq0 \quad \text{for all }\mathbf{u},\theta\in\mathbb R^k.

The quadratic form u2F(θ)u\mathbf{u}^\top\nabla^2F(\theta)\,\mathbf{u} is the second derivative of FF along the line through θ\theta in direction u\mathbf{u}, so the theorem says exactly that FF is convex if and only if its restriction to every line has nonnegative second derivative.

Let us apply this test to the logistic-regression loss.

Theorem 1.10 (convexity and smoothness of the logistic loss). Let R=maxiviR=\max_i\|\mathbf{v}_i\|. Then the logistic-regression loss L\mathcal L is convex. Moreover, its curvature is bounded: for every θ\theta and every direction uRd+1\mathbf{u}\in\mathbb R^{d+1},

0    u2L(θ)u    R24u2.0 \;\leq\; \mathbf{u}^\top\nabla^2\mathcal L(\theta)\,\mathbf{u} \;\leq\; \frac{R^2}{4}\,\|\mathbf{u}\|^2.
Proof

We recap the setting from above: the parameter is θ=(w,b)\theta=(\mathbf{w},b), the training samples are (xi,yi)i=1N(\mathbf{x}_i,y_i)_{i=1}^N, and the probabilities are y^i=σ(wxi+b)\widehat y_i=\sigma(\mathbf{w}^\top\mathbf{x}_i+b). In the gradient we computed in Section 1, the parameter and each feature vector appear with one extra coordinate appended, the bias bb in one case and the constant 11 in the other, so it is worth naming the stacked vectors. Write

vi=(xi1),θ=(wb)Rd+1,\mathbf{v}_i= \begin{pmatrix} \mathbf{x}_i\\ 1 \end{pmatrix}, \qquad \theta= \begin{pmatrix} \mathbf{w}\\ b \end{pmatrix} \in\mathbb R^{d+1},

so that zi=θviz_i=\theta^\top\mathbf{v}_i, y^i=σ(zi)\widehat y_i=\sigma(z_i), and the gradient reads

L(θ)=1Ni=1N(y^iyi)vi.\nabla\mathcal L(\theta) = \frac1N\sum_{i=1}^N(\widehat y_i-y_i)\mathbf{v}_i.

Differentiate the gradient once more. The only dependence on θ\theta on the right side of the gradient formula is through y^i=σ(θvi)\widehat y_i=\sigma(\theta^\top\mathbf{v}_i), so by the chain rule and the sigmoid derivative σ=σ(1σ)\sigma'=\sigma(1-\sigma),

y^i=σ(θvi)(θvi)=y^i(1y^i)vi.\nabla \widehat y_i = \sigma'\bigl(\theta^\top\mathbf{v}_i\bigr)\,\nabla\bigl(\theta^\top\mathbf{v}_i\bigr) = \widehat y_i(1-\widehat y_i)\,\mathbf{v}_i.

The iith summand of the gradient is the fixed vector vi\mathbf{v}_i scaled by y^iyi\widehat y_i-y_i, so its derivative in θ\theta is vi\mathbf{v}_i times the row vector (y^i)(\nabla \widehat y_i)^\top, that is, the outer product y^i(1y^i)vivi\widehat y_i(1-\widehat y_i)\mathbf{v}_i\mathbf{v}_i^\top. Averaging the summands,

2L(θ)=1Ni=1Ny^i(1y^i)vivi.\nabla^2\mathcal L(\theta) = \frac1N\sum_{i=1}^N \widehat y_i(1-\widehat y_i)\mathbf{v}_i\mathbf{v}_i^\top.

For any u\mathbf{u},

u2L(θ)u=1Ni=1Ny^i(1y^i)(uvi)20.\mathbf{u}^\top\nabla^2\mathcal L(\theta)\,\mathbf{u} = \frac1N\sum_{i=1}^N \widehat y_i(1-\widehat y_i)(\mathbf{u}^\top\mathbf{v}_i)^2 \geq0.

Thus the Hessian is positive semidefinite at every θ\theta, and by the second-order test, L\mathcal L is convex.

For the upper bound, we estimate each summand twice over. First, the function ss(1s)s\mapsto s(1-s) on [0,1][0,1] attains its maximum 1/41/4 at s=1/2s=1/2, so y^i(1y^i)1/4\widehat y_i(1-\widehat y_i)\leq1/4. Second, by the Cauchy–Schwarz inequality,

(uvi)2u2vi2R2u2.(\mathbf{u}^\top\mathbf{v}_i)^2 \leq \|\mathbf{u}\|^2\|\mathbf{v}_i\|^2 \leq R^2\|\mathbf{u}\|^2.

Each summand is therefore at most R24u2\tfrac{R^2}{4}\|\mathbf{u}\|^2, and so is their average. \square

Recall from the discussion of the second-order test that u2L(θ)u\mathbf{u}^\top\nabla^2\mathcal L(\theta)\,\mathbf{u} is the second derivative of L\mathcal L along the line through θ\theta in direction u\mathbf{u}. The upper bound in the theorem therefore says that the gradient cannot change arbitrarily fast: along any unit direction, the second derivative of the loss is at most R2/4R^2/4.

Theorem 1.11 (a baby gradient-descent guarantee). Consider a logistic regression model. Set M=R2/4M=R^2/4, with R=maxiviR=\max_i\|\mathbf{v}_i\| as above, and suppose L(θ)\mathcal{L}(\theta) has a finite minimizer θ^\widehat\theta (Definition 0.4). If the learning rate satisfies 0<η1/M0<\eta\leq1/M, then gradient descent (Definition 1.2, applied to F=LF=\mathcal L) satisfies

0L(θ(t))L(θ^)θ(0)θ^22ηt0 \le \mathcal L(\theta^{(t)})-\mathcal L(\widehat\theta) \leq \frac{\|\theta^{(0)}-\widehat\theta\|^2}{2\eta t}

for every t1t\geq1. In particular, the loss values converge to the global minimum.

Proof sketch

A differentiable convex function with Hessian bounded above by MIMI satisfies the standard smooth-convex inequality

L(θ),θθ^L(θ)L(θ^)+12ML(θ)2.\left\langle \nabla\mathcal L(\theta), \theta-\widehat\theta \right\rangle \geq \mathcal L(\theta)-\mathcal L(\widehat\theta) + \frac{1}{2M}\|\nabla\mathcal L(\theta)\|^2.

Insert the update θ+=θηL(θ)\theta^+=\theta-\eta\nabla\mathcal L(\theta) into θ+θ^2\|\theta^+-\widehat\theta\|^2. Expanding the square and using the displayed inequality, together with η1/M\eta\leq1/M, gives

2η[L(θ)L(θ^)]θθ^2θ+θ^2.2\eta\left[ \mathcal L(\theta)-\mathcal L(\widehat\theta) \right] \leq \|\theta-\widehat\theta\|^2 - \|\theta^+-\widehat\theta\|^2.

Apply this at iterations 0,,t10,\ldots,t-1 and sum. The right side telescopes. The loss is non-increasing for this step size, so its final gap is at most the average of the preceding gaps, which gives the claimed bound. \square

Let us make a few notes on the hypotheses.

First, the restriction η1/M\eta\leq1/M is necessary: a learning rate that is too large can overshoot. For a simple example, consider linear regression (not logistic regression). In that case, the loss looks like a parabola L(θ)=M2θ2\mathcal{L}(\theta)=\tfrac{M}{2}\theta^2. One gradient step looks like

θ(t+1)=θ(t)ηMθ(t)=(1ηM)θ(t).\theta^{(t+1)}=\theta^{(t)}-\eta M\theta^{(t)}=(1-\eta M)\,\theta^{(t)}.

In this example, if η<2/M\eta<2/M, the factor 1ηM1-\eta M has absolute value less than 11 and the iterates converge to the minimum at 00; but if η>2/M\eta>2/M, the factor has absolute value greater than 11, and each step jumps past the minimum to a point farther away than where it started. The iterates oscillate in sign with growing amplitude, and the loss diverges.

θ⁽⁰⁾ θ⁽¹⁾ θ⁽²⁾ θ⁽⁰⁾ θ⁽¹⁾ θ⁽²⁾ θ⁽³⁾ θ⁽⁴⁾ θ⁽³⁾ η = 1.5/M: overshoot, but converge η = 2.5/M: overshoot and diverge θ
Gradient descent on the parabola ℒ(θ) = Mθ²/2, where one step multiplies θ by the factor 1 − ηM. Left: η = 1.5/M; right: η = 2.5/M.

Second, the theorem assumes that a finite minimizer θ^\widehat\theta exists. This can fail. Call a training pair (x,y)(\mathbf{x},y) a positive sample if its gold label is y=1y=1, and a negative sample if y=0y=0. A binary dataset is linearly separable if some affine hyperplane places the feature vector of every positive sample strictly on one side and the feature vector of every negative sample strictly on the other. It turns out that if the data are separable, the infimum is never attained by any finite parameter, and the theorem does not apply. The converse is nearly true: a classical dichotomy of Albert and Anderson says that a finite minimizer exists if and only if the data cannot even be weakly separated, i.e. there is no nonzero (w,b)(\mathbf{w},b) with wx+b0\mathbf{w}^\top\mathbf{x}+b\geq0 for every positive sample and 0\leq0 for every negative sample. In particular, strictly separable data never admit a finite minimizer.

Why does separability exhibit this behaviour? Imagine our training samples are very clearly delineated: imagine that the ones with gold label 11 are in one cluster and the ones with gold label 00 in another cluster, and the two clusters are nicely separated in space so that a hyperplane can pass between them. Suppose one such hyperplane is of the form {x:wx+b=0}\{ \mathbf{x} : \mathbf{w}^\top \mathbf{x} + b = 0 \} for some wRd\mathbf{w} \in \mathbb R^d and bRb \in \mathbb R. Then θ=(w,b)\theta = (\mathbf{w}, b) is an excellent choice for the model parameters, since the logit z=wx+bz = \mathbf{w}^\top \mathbf{x} + b will then take on positive values on one side of the hyperplane and negative values on the other. To get a good model (one which assigns high probabilities to the gold labels), we want the logit to take on positive values on the side with the cluster of positive samples; if we didn’t make the right choice, just replace θ\theta with θ-\theta to fix it.

𝐰𝐱 + b = 0 y = 0 y = 1 p(y = 0) > 1/2 p(y = 1) > 1/2
A linearly separable dataset: the hyperplane 𝐰𝐱 + b = 0 places the negative samples (open red circles) strictly on one side and the positive samples (filled blue circles) strictly on the other.

Under this setup, the model assigns probability exceeding 1/21/2 to every gold label in the training set. But if we replace θ\theta with λθ=(λw,λb)\lambda \theta = (\lambda \mathbf{w}, \lambda b), for some large positive λR\lambda \in \mathbb R, we do even better, because we assign probabilities closer to 11. As λ\lambda \rightarrow \infty, we get zz \rightarrow \infty on the positive samples and zz \rightarrow -\infty on the negative samples. And the probabilities assigned to the gold labels approach 11. So the best parameter choice, in some sense, is to let λ\lambda approach \infty. In other words, there’s no global minimum to the loss: the loss looks something like the blue two-sample curve in Example 1.7.

The standard repair, when a finite minimizer is wanted, is to add a penalty, or regularizer: an extra term, added to the loss, that grows as the parameters grow, so that large parameters are penalized. The most common choice is the penalty λθ2\lambda\|\theta\|^2 with λ>0\lambda>0 — that is, we minimize L(θ)+λθ2\mathcal L(\theta)+\lambda\|\theta\|^2 instead of L(θ)\mathcal L(\theta). This works because the penalized objective tends to ++\infty as θ\|\theta\|\to\infty, so it attains a finite minimizer even on separable data, at the price of a small bias toward small weights. The penalty also improves the curvature. Its Hessian, as a function of θ\theta, is 2λI2\lambda I, where II denotes the identity matrix, so the penalized objective has Hessian bounded below by 2λI2\lambda I; a function whose Hessian is bounded below by μI\mu I for some μ>0\mu>0 is called strongly convex. Strong convexity guarantees a unique minimizer, and for such objectives gradient descent converges geometrically — the error shrinks by a constant factor each step — rather than at the slower 1/t1/t rate of Theorem 1.11.


2. Softmax and the simplex

Binary logistic regression produces a distribution on two labels. A language model needs a distribution on an entire vocabulary V\mathcal{V} (Lecture 1, Section 0). Therefore, let C:=V\mathcal{C} := \mathcal{V}, so that the number of possible labels is V=VV=|\mathcal V|, and write

ΔV1=Δ(V)={pRV:pb0, b=1Vpb=1}.\Delta^{V-1} = \Delta(\mathcal{V}) = \left\{ p\in\mathbb R^V: p_b\geq0,\ \sum_{b=1}^Vp_b=1 \right\}.

This is the probability simplex from Lecture 1. Its relative interior is

relintΔV1={pΔV1:pb>0 for every b}.\operatorname{relint}\Delta^{V-1} = \left\{ p\in\Delta^{V-1}:p_b>0\text{ for every }b \right\}.

It is called a relative interior because the simplex lies in the affine hyperplane bpb=1\sum_b p_b=1, which has dimension V1V-1 rather than VV. So we are taking its interior with respect to this hyperplane.

V = 2 e₁ = (1, 0) e₂ = (0, 1) relint Δ¹ p₁ + p₂ = 1 p₁ p₂
V = 3 e₁ e₂ e₃ 0 p₁ p₂ p₃ relint Δ² p₁ + p₂ + p₃ = 1
The simplex and its relative interior. Left: Δ¹ is a segment in the line p₁ + p₂ = 1 ⊂ ℝ², and relint Δ¹ is the segment without its endpoints. Right: the blue patch shows part of the plane p₁ + p₂ + p₃ = 1 ⊂ ℝ³. That plane meets the three coordinate axes at e₁, e₂, and e₃; their convex hull is the triangle Δ². Its purple interior is relint Δ², where all three coordinates are positive, and its edges form the boundary.

Definition 2.1 (softmax). For a vector z=(z1,,zV)RVz=(z_1,\ldots,z_V)^\top\in\mathbb R^V, define

softmax:RVrelintΔV1,zsoftmax(z)=ezc=1Vezc=(ez1,,ezV)c=1Vezc.\operatorname{softmax}:\mathbb R^V \longrightarrow\operatorname{relint}\Delta^{V-1}, \qquad z\longmapsto \operatorname{softmax}(z) = \frac{e^z}{\sum_{c=1}^V e^{z_c}} = \frac{(e^{z_1},\ldots,e^{z_V})^\top} {\sum_{c=1}^V e^{z_c}}.

For V=2V=2, write z=(z1,z2)z=(z_1,z_2)^\top. The second softmax coordinate is a sigmoid of the logit difference:

softmax(z)2=ez2ez1+ez2=11+e(z2z1)=σ(z2z1).\operatorname{softmax}(z)_2 = \frac{e^{z_2}}{e^{z_1}+e^{z_2}} = \frac{1}{1+e^{-(z_2-z_1)}} = \sigma(z_2-z_1).

The first coordinate is 1softmax(z)21-\operatorname{softmax}(z)_2, which carries the same information. Thus two-class softmax gives exactly the binary distribution of Section 0 if one uses z2z1z_2-z_1 as the binary logit and discards the redundant first coordinate in favour of the second one.

Each coordinate ezb/cezce^{z_b}/\sum_c e^{z_c} is positive, and the coordinates sum to 11, so softmax does land in relintΔV1\operatorname{relint}\Delta^{V-1}, as the stated codomain asserts. The entries zbz_b of the input vector are called logits, extending the terminology of Definition 0.2.

Recall from Definition 0.1 that for an event of probability pp, the odds are p/(1p)p/(1-p) and the logit is the log-odds log(p/(1p))\log\bigl(p/(1-p)\bigr). With VV labels, the natural analogue compares two labels at a time: given a distribution prelintΔV1p\in\operatorname{relint}\Delta^{V-1}, the ratio pb/pcp_b/p_c is the odds of label bb against label cc, and log(pb/pc)\log(p_b/p_c) is their pairwise log-odds. For softmax the pairwise log-odds have an extremely simple form:

logsoftmax(z)bsoftmax(z)c=zbzc.\log \frac{\operatorname{softmax}(z)_b} {\operatorname{softmax}(z)_c} = z_b-z_c.

Thus only differences between logits matter to the output distribution: the pairwise odds depend on zz only through the differences zbzcz_b-z_c, and since a probability vector is determined by its coordinate ratios (the coordinates must sum to 11), so does softmax(z)\operatorname{softmax}(z) itself. In particular, adding the same constant to every logit leaves the output unchanged.

Example 2.2 (softmax by inspection). Take the logits

z=(0,log2,log3).z=(0,\log2,\log3).

Then

(ez1,ez2,ez3)=(1,2,3),(e^{z_1},e^{z_2},e^{z_3})=(1,2,3),

and hence

softmax(z)=(16,26,36).\operatorname{softmax}(z) = \left(\frac16,\frac26,\frac36\right).

The third label has three times the odds of the first because z3z1=log3z_3-z_1=\log3. Adding 1010 to all three logits changes the exponentials to (e10,2e10,3e10)(e^{10},2e^{10},3e^{10}) and changes none of the probabilities.

The preceding example reveals that softmax has one redundant direction. We now describe the geometry precisely. Let 1=(1,,1)RV\mathbf1=(1,\ldots,1)^\top\in\mathbb R^V, let

1={zRV:1z=0},\mathbf1^\perp = \{z\in\mathbb R^V:\mathbf1^\top z=0\},

and for uRVu\in\mathbb R^V write

mean(u)=1Vb=1Vub.\operatorname{mean}(u)=\frac1V\sum_{b=1}^Vu_b.

That is, 1\mathbf1^\perp is the kernel of the mean: those vectors zz whose mean is zero.

A diffeomorphism is a smooth bijection with a smooth inverse.

Proposition 2.3 (softmax as a diffeomorphism to the open simplex). Softmax has the following properties.

  1. Its image is relintΔV1\operatorname{relint}\Delta^{V-1}.

  2. It is invariant under a common shift:

    softmax(z+c1)=softmax(z)\operatorname{softmax}(z+c\mathbf1) = \operatorname{softmax}(z)

    for every cRc\in\mathbb R.

  3. Its restriction

    softmax1:1relintΔV1\left.\operatorname{softmax}\right|_{\mathbf1^\perp}: \mathbf1^\perp \longrightarrow \operatorname{relint}\Delta^{V-1}

    is a diffeomorphism. The inverse is

    g(p)=logpmean(logp)1,mean(logp)=1Vb=1Vlogpb,g(p) = \log p-\operatorname{mean}(\log p)\,\mathbf1, \qquad \operatorname{mean}(\log p) = \frac1V\sum_{b=1}^V\log p_b,

    where logarithms are taken coordinatewise.

In other words, for the differential geometer, softmax restricted to the zero-mean logits is a global coordinate chart on the open simplex: every strictly positive probability vector has exactly one zero-mean logit vector as coordinates, and passing between the two descriptions is smooth in both directions.

Proof

We already observed that softmax has positive coordinates summing to 11, so its image is contained in the relative interior. In the other direction, take prelintΔV1p\in\operatorname{relint}\Delta^{V-1}. Every logarithm is defined, and

softmax(logp)b=elogpbcelogpc=pbcpc=pb.\operatorname{softmax}(\log p)_b = \frac{e^{\log p_b}}{\sum_c e^{\log p_c}} = \frac{p_b}{\sum_c p_c} = p_b.

This proves the first assertion.

For any scalar cc,

softmax(z+c1)b=ezb+crezr+c=ecezbecrezr=softmax(z)b.\begin{aligned} \operatorname{softmax}(z+c\mathbf1)_b &= \frac{e^{z_b+c}}{\sum_r e^{z_r+c}}\\ &= \frac{e^ce^{z_b}}{e^c\sum_r e^{z_r}}\\ &= \operatorname{softmax}(z)_b. \end{aligned}

This proves shift invariance. Every affine line z+R1z+\mathbb R\mathbf1 contains exactly one zero-mean representative,

z0=zmean(z)1.z^0=z-\operatorname{mean}(z)\,\mathbf1.

Indeed, z01z^0\in\mathbf1^\perp, while z+c1z+c\mathbf1 has mean mean(z)+c\operatorname{mean}(z)+c.

It remains to verify the inverse. For prelintΔV1p \in \operatorname{relint}\Delta^{V-1}, the vector g(p)g(p) has mean zero. Shift invariance and the first calculation give

softmax(g(p))=softmax(logp)=p.\operatorname{softmax}(g(p)) = \operatorname{softmax}(\log p) = p.

Conversely, take z1z\in\mathbf1^\perp and set S=cezcS=\sum_c e^{z_c}. Coordinatewise,

log(softmax(z))=z(logS)1.\log(\operatorname{softmax}(z)) = z-(\log S)\mathbf1.

Since zz has mean zero, the mean of the vector on the right is logS-\log S. Subtracting this mean recovers zz, so

g(softmax(z))=z.g(\operatorname{softmax}(z))=z.

Softmax is smooth because it is built from exponentials with a positive denominator, and gg is smooth where every pb>0p_b>0. The restricted map is therefore a diffeomorphism. \square

Restricting to zero-mean logits is one way to choose a unique representation. Fixing a specified logit to be zero is another.

𝟏⊥ = {z : z₁ + z₂ + z₃ = 0} p₁ + p₂ + p₃ = 1 relint Δ² e₁ e₂ e₃ 0 𝟏 barycenter
The geometry of Proposition 2.3 for V = 3. The blue plane 𝟏 of zero-mean logits passes through the origin. The plane p₁ + p₂ + p₃ = 1 is a parallel translate in the all-ones direction; it contains the same simplex triangle shown in the preceding figure. The vector 𝟏 pierces that triangle at its barycenter (⅓, ⅓, ⅓). Softmax carries the entire blue plane diffeomorphically onto the purple interior of the triangle.

The term identifiable means that different parameter values produce different modeled distributions. Unrestricted softmax logits are not identifiable: zz and z+c1z+c\mathbf1 represent the same distribution. Their differences are identifiable.


3. Multinomial logistic regression

We now repeat binary logistic regression with VV possible labels. The parallel is exact:

binary classificationVV-class classification
one logit zRz\in\mathbb Ra vector of logits zRVz\in\mathbb R^V
sigmoidsoftmax
Bernoulli distributioncategorical distribution
scalar error y^y\widehat y-yvector error peyp-e_y
affine decision boundarypairwise affine decision boundaries

The logits will again be affine functions of the features.

Definition 3.1 (multinomial logistic regression). Let C={1,,V}\mathcal C=\{1,\ldots,V\} be a set of classes and let X=Rd\mathcal X=\mathbb R^d be the feature vector space. For a parameter

θ=(W,β)Θ:=Rd×V×RV,\theta=(W,\beta)\in \Theta:=\mathbb R^{d\times V}\times\mathbb R^V,

define the logit map

zθ:XRV,zθ(x)=Wx+β.z_\theta:\mathcal X\longrightarrow\mathbb R^V, \qquad z_\theta(\mathbf{x})=W^\top\mathbf{x}+\beta.

Writing wj=W:,jRd\mathbf w_j=W_{:,j}\in\mathbb R^d for the jjth column of WW, its jjth coordinate is

zj(x)=wjx+βj.z_j(\mathbf{x}) = \mathbf w_j^\top\mathbf{x}+\beta_j.

Here the colon in W:,jW_{:,j} means “all row indices,” so W:,jW_{:,j} is a column; similarly, Wi,:W_{i,:} denotes the entire iith row. The entries of WW are the weights, the entries of β\beta are the biases, and the coordinates zj(x)z_j(\mathbf{x}) are the logits.

The associated multinomial logistic regression model, or softmax regression model, is the probabilistic classifier

P:Θ×XrelintΔV1P:\Theta\times\mathcal X \longrightarrow\operatorname{relint}\Delta^{V-1}

defined by

P(θ,x)=pθ(x)=softmax(zθ(x)).P(\theta,\mathbf{x}) = p_\theta(\,\cdot\mid\mathbf{x}) = \operatorname{softmax}(z_\theta(\mathbf{x})).

Thus, for jCj\in\mathcal C,

pθ(y=jx)=exp(zj(x))r=1Vexp(zr(x)).p_\theta(y=j\mid\mathbf{x}) = \frac{\exp(z_j(\mathbf{x}))} {\sum_{r=1}^V\exp(z_r(\mathbf{x}))}.

We also write pW,βp_{W,\beta} for pθp_\theta. When θ\theta and x\mathbf{x} are fixed, we abbreviate pj:=pθ(y=jx)p_j:=p_\theta(y=j\mid\mathbf{x}).

The most probable label is the one with largest logit. The decision boundary between labels jj and rr is

zj(x)=zr(x),z_j(\mathbf{x})=z_r(\mathbf{x}),

or equivalently

(wjwr)x+(βjβr)=0.(\mathbf w_j-\mathbf w_r)^\top\mathbf{x} +(\beta_j-\beta_r)=0.

It is a hyperplane. The pairwise boundaries divide X=Rd\mathcal X=\mathbb R^d into polyhedral regions. Within each region, the ordering of the logits—and hence the ordering of the class probabilities—is fixed.

Aside 3.1a (the two-class case). Let V=2V=2, with logits z1,z2z_1,z_2, and identify class 22 with the positive label of binary logistic regression. Then

pθ(y=2x)=ez2ez1+ez2=σ(z2z1).p_\theta(y=2\mid\mathbf{x}) = \frac{e^{z_2}}{e^{z_1}+e^{z_2}} = \sigma(z_2-z_1).

The probability of class 11 is 1pθ(y=2x)1-p_\theta(y=2\mid\mathbf{x}). Therefore two-class softmax regression is precisely binary logistic regression with the single identifiable logit z2z1z_2-z_1. Adding the same constant to both logits changes neither probability.

For next-token prediction, take C=V\mathcal C=\mathcal V. The feature vector x\mathbf{x} is a numerical representation of the context, and the observed class yy is the next token.

For a target class j{1,,V}j\in\{1,\ldots,V\}, let ejRVe_j\in\mathbb R^V denote its one-hot vector: coordinate jj is 11 and every other coordinate is 00 (a pure mathematician would call this a standard basis vector 🙃). We will use the indicator notation

1{A}={1,if the statement A is true,0,if it is false.\mathbf1_{\{A\}} = \begin{cases} 1,&\text{if the statement }A\text{ is true},\\ 0,&\text{if it is false}. \end{cases}

Thus (ey)j=1{j=y}(e_y)_j=\mathbf1_{\{j=y\}}.

Definition 3.2 (categorical cross-entropy). For logits z=Wx+βRVz=W^\top\mathbf{x}+\beta\in\mathbb R^V, probabilities p=softmax(z)relintΔV1p=\operatorname{softmax}(z)\in\operatorname{relint}\Delta^{V-1}, and target yy, the one-sample categorical cross-entropy loss (also log loss) is

(W,β;x,y)=logpy=j=1V(ey)jlogpj=zy+logj=1Vezj.\begin{aligned} \ell(W,\beta;\mathbf{x},y) &=-\log p_y\\ &=-\sum_{j=1}^V(e_y)_j\log p_j\\ &=-z_y+\log\sum_{j=1}^V e^{z_j}. \end{aligned}

For training samples {(xi,yi)}i=1N\{(\mathbf{x}_i,y_i)\}_{i=1}^N, the empirical loss (also average negative log likelihood or cost) is

L(W,β)=1Ni=1N(W,β;xi,yi).\mathcal L(W,\beta) = \frac1N\sum_{i=1}^N \ell(W,\beta;\mathbf{x}_i,y_i).

These are the quantities of Definition 0.4, specialized to the softmax model. They follow the same maximum-likelihood recipe as Lecture 1, Section 3.

Example 3.3 (one three-class prediction). Suppose

z=(0,log2,log3)z=(0,\log2,\log3)^\top

and the observed class is y=2y=2. Example 2.2 gives

p=(16,13,12).p=\left(\frac16,\frac13,\frac12\right)^\top.

The loss is

=logp2=log31.099.\ell=-\log p_2=\log3\approx1.099.

If the observed class were 33, the loss would instead be log(1/2)=log20.693-\log(1/2)=\log2\approx0.693. The probability vector is unchanged; only the observed coordinate changes.

Fix one sample (x,y)(\mathbf{x},y). We next differentiate through the logits z=Wx+βz=W^\top\mathbf{x}+\beta.

Proposition 3.4 (gradient of the multinomial log loss). In this setup,

z=pey,W=x(pey),β=pey.\boxed{ \nabla_z\ell=p-e_y, \qquad \nabla_W\ell=\mathbf{x}(p-e_y)^\top, \qquad \nabla_\beta\ell=p-e_y. }

The three gradients lie in RV\mathbb R^V, Rd×V\mathbb R^{d\times V}, and RV\mathbb R^V, respectively.

Proof

The loss depends on (W,β)(W,\beta) only through the VV logits zj=wjx+βjz_j=\mathbf w_j^\top\mathbf{x}+\beta_j. As a function of zz,

=zy+logr=1Vezr.\ell=-z_y+\log\sum_{r=1}^V e^{z_r}.

For each jj,

zj=1{j=y}+ezjrezr=pj1{j=y}.\begin{aligned} \frac{\partial\ell}{\partial z_j} &= -\mathbf1_{\{j=y\}} + \frac{e^{z_j}}{\sum_r e^{z_r}}\\ &= p_j-\mathbf1_{\{j=y\}}. \end{aligned}

Hence z=pey\nabla_z\ell=p-e_y. Since wjzj=x\nabla_{\mathbf w_j}z_j=\mathbf{x} and zj/βj=1\partial z_j/\partial\beta_j=1,

wj=(pj1{j=y})x,βj=pj1{j=y}.\nabla_{\mathbf w_j}\ell = (p_j-\mathbf1_{\{j=y\}})\mathbf{x}, \qquad \frac{\partial\ell}{\partial\beta_j} = p_j-\mathbf1_{\{j=y\}}.

Assembling the weight derivatives column by column gives W=x(pey)\nabla_W\ell=\mathbf{x}(p-e_y)^\top. \square

The logit-gradient coordinates sum to zero:

1(pey)=11=0,\mathbf1^\top(p-e_y)=1-1=0,

where 1=(1,,1)RV\mathbf1=(1,\ldots,1)^\top\in\mathbb R^V. This had to happen: the loss is unchanged when every logit receives a common shift, so its directional derivative along 1\mathbf1 vanishes.

The weight gradient is an outer product. Its jjth column is (pj1{j=y})x(p_j-\mathbf1_{\{j=y\}})\mathbf{x}: prediction error for class jj, times the feature vector. In the two-class setting of Aside 3.1a, the two coordinates are opposites. If q=pθ(y=2x)q=p_\theta(y=2\mid\mathbf{x}) and the target is class 22, then

pe2=(1q,q1),p-e_2=(1-q,q-1)^\top,

which is the binary derivative q1q-1 expressed in the redundant two-logit coordinates.

For Example 3.3,

z=(16,23,12).\nabla_z\ell = \left(\frac16,-\frac23,\frac12\right)^\top.

A negative-gradient step raises the target logit relative to the other two: it adds 2η/32\eta/3 to z2z_2 while subtracting η/6\eta/6 from z1z_1 and η/2\eta/2 from z3z_3.

Over a training set, the empirical gradient is the average of the per-sample gradients. We can compute all samples at once by collecting them row by row.

Algorithm 3.5 (gradient descent for softmax regression).

Input: a feature matrix XRN×dX\in\mathbb R^{N\times d} whose iith row is xi\mathbf{x}_i^\top; a one-hot label matrix YRN×VY\in\mathbb R^{N\times V} whose iith row is eyie_{y_i}^\top; a learning rate η>0\eta>0; a number of steps TT; and initial parameters W(0)Rd×VW^{(0)}\in\mathbb R^{d\times V} and β(0)RV\beta^{(0)}\in\mathbb R^V. Let 1N=(1,,1)RN\mathbf1_N=(1,\ldots,1)^\top\in\mathbb R^N.

For t=0,1,,T1t=0,1,\ldots,T-1:

  1. Compute the logit matrix and probability matrix

    Z(t)=XW(t)+1N(β(t))RN×V,P(t)=softmax(Z(t))RN×V,Z^{(t)} = XW^{(t)}+\mathbf1_N(\beta^{(t)})^\top \in\mathbb R^{N\times V}, \qquad P^{(t)} = \operatorname{softmax}(Z^{(t)}) \in\mathbb R^{N\times V},

    where softmax acts on each row. Row ii of Z(t)Z^{(t)} is (zi(t))R1×V(z_i^{(t)})^\top\in\mathbb R^{1\times V}, and row ii of P(t)P^{(t)} is (pi(t))R1×V(p_i^{(t)})^\top\in\mathbb R^{1\times V}.

  2. Form the error matrix

    R(t)=P(t)YRN×V.R^{(t)} = P^{(t)}-Y \in\mathbb R^{N\times V}.

    Its iith row is (pi(t)eyi)(p_i^{(t)}-e_{y_i})^\top.

  3. Compute the two gradient blocks:

    WL=1NXR(t)Rd×V,βL=1N(R(t))1NRV.\nabla_W\mathcal L = \frac1N X^\top R^{(t)} \in\mathbb R^{d\times V}, \qquad \nabla_\beta\mathcal L = \frac1N(R^{(t)})^\top\mathbf1_N \in\mathbb R^V.
  4. Update within the same parameter spaces:

    W(t+1)=W(t)ηWLRd×V,β(t+1)=β(t)ηβLRV.W^{(t+1)} = W^{(t)}-\eta\nabla_W\mathcal L \in\mathbb R^{d\times V}, \qquad \beta^{(t+1)} = \beta^{(t)}-\eta\nabla_\beta\mathcal L \in\mathbb R^V.

Output: W(T)Rd×VW^{(T)}\in\mathbb R^{d\times V} and β(T)RV\beta^{(T)}\in\mathbb R^V.

A minibatch is a small randomly chosen subset of the training samples. Minibatch methods use the same formulas with the average over a fresh minibatch in place of the average over all NN samples. Each step becomes much cheaper, at the price of a noisy estimate of the full gradient.

Proposition 3.6 (convexity of softmax regression). For fixed features, the empirical cross-entropy loss L\mathcal L is convex in (W,β)(W,\beta). The one-sample Hessian with respect to the logits is the V×VV\times V matrix

z2=diag(p)pp,\nabla_z^2\ell = \operatorname{diag}(p)-pp^\top,

which is positive semidefinite.

Proof

Differentiating pj=ezj/rezrp_j=e^{z_j}/\sum_r e^{z_r} gives

pjzk=pj(1{j=k}pk).\frac{\partial p_j}{\partial z_k} = p_j(\mathbf1_{\{j=k\}}-p_k).

This is the (j,k)(j,k) entry of diag(p)pp\operatorname{diag}(p)-pp^\top. For every uRVu\in\mathbb R^V,

u(diag(p)pp)u=jpjuj2(jpjuj)2=VarJp(uJ)0.\begin{aligned} u^\top\left(\operatorname{diag}(p)-pp^\top\right)u &= \sum_jp_ju_j^2-\left(\sum_jp_ju_j\right)^2\\ &= \operatorname{Var}_{J\sim p}(u_J) \geq0. \end{aligned}

Thus the loss is convex in zz. Since zz is affine in (W,β)(W,\beta), composition with this affine map preserves convexity, as does averaging over samples. \square


4. From individual units to feedforward networks

To increase expressiveness, we can combine “units” of logistic regression into networks.

4.1 Artificial neurons

Definition 4.1 (unit). A unit, or artificial neuron, is a function RdR\mathbb R^d \rightarrow \mathbb R taking a feature vector to a value:

xϕ(wx+b),\mathbf{x} \mapsto \phi(\mathbf{w}^\top \mathbf{x} + b),

where ϕ:RR\phi: \mathbb R \rightarrow \mathbb R is a fixed function called the activation function, the vector wRd\mathbf{w}\in\mathbb R^d contains the weights wiw_i, and the scalar bb is the bias. The intermediate value a=wx+ba=\mathbf{w}^\top\mathbf{x}+b is the preactivation, and the output value h=ϕ(a)h=\phi(a) is the activation of the unit.

We have already met a unit: binary logistic regression (Definition 0.2) computes exactly one unit, with the sigmoid as its activation function. The activation function is ϕ=σ\phi=\sigma; the weights w\mathbf{w} and bias bb of the unit are the weights and bias of the logistic regression model; the preactivation a=wx+ba=\mathbf{w}^\top\mathbf{x}+b is the logit zθ(x)z_\theta(\mathbf{x}); and the activation h=σ(a)h=\sigma(a) is the predicted probability pθ(y=1x)=y^p_\theta(y=1\mid\mathbf{x})=\widehat y.

(Softmax regression is close to being a collection of VV units, one per logit, but not quite: the softmax is applied jointly to the whole logit vector, rather than to each preactivation separately.)

One historically important activation is the step function

H(t)={0,t<0,1,t0.H(t) = \begin{cases} 0,&t<0,\\ 1,&t\geq0. \end{cases}

A unit xH(wx+b)\mathbf{x}\mapsto H(\mathbf{w}^\top\mathbf{x}+b), i.e. a unit using the step function activation, is called a perceptron. It makes a hard binary decision separated by a hyperplane in Rd\mathbb R^d.

The first question to ask is how expressive such units are. This is the question of what space of possible functions they represent.

The Boolean exclusive-or function, or XOR, is the function XOR:{0,1}×{0,1}{0,1}\operatorname{XOR} : \{0,1\} \times \{0,1\} \rightarrow \{0,1\} given by

x1x_1x2x_2XOR(x1,x2)\operatorname{XOR}(x_1,x_2)
000000
110011
001111
111100

Theorem 4.2 (one perceptron cannot compute XOR). There are no w1,w2,bRw_1,w_2,b\in\mathbb R such that

H(w1x1+w2x2+b)=XOR(x1,x2)H(w_1x_1+w_2x_2+b) = \operatorname{XOR}(x_1,x_2)

at all four points of {0,1}2\{0,1\}^2.

Proof

Correct classification at (0,0)(0,0) requires

b<0.b<0.

Correct classification at (1,0)(1,0) and (0,1)(0,1) requires

w1+b0,w2+b0.w_1+b\geq0, \qquad w_2+b\geq0.

Adding these two inequalities gives w1+w2+2b0w_1+w_2+2b\geq0. Since b<0b<0,

w1+w2+bb>0.w_1+w_2+b\geq-b>0.

But correct classification at (1,1)(1,1) requires w1+w2+b<0w_1+w_2+b<0, a contradiction. \square

A line cannot separate the two positive XOR points (1,0),(0,1)(1,0),(0,1) from the two negative points (0,0),(1,1)(0,0),(1,1). The convex hull of each pair is the diagonal segment joining it, and the two segments cross at (1/2,1/2)(1/2,1/2). A hyperplane separator would have to put their convex hulls on opposite sides, which is impossible.

The obstruction is not that XOR is somehow mysterious. It is that one affine decision boundary has the wrong geometry. The AND and OR functions are linearly separable (you can check this).

4.2 Combining units into networks

The rectified linear unit is

ReLU(t)=max{0,t}.\operatorname{ReLU}(t)=\max\{0,t\}.

Unlike the perceptron, it retains the size of a positive preactivation. Consider two units

h1=ReLU(x1+x2),h2=ReLU(x1+x21),h_1=\operatorname{ReLU}(x_1+x_2), \qquad h_2=\operatorname{ReLU}(x_1+x_2-1),

and a third unit, taking (h1,h2)(h_1,h_2) as its input:

f(x1,x2)=ReLU(h12h2).f(x_1,x_2)=\operatorname{ReLU}(h_1-2h_2).

We will now string these together. The diagram below shows how the units should be imagined as being arranged in layers. The final unit(s) are the output unit(s) — those whose results are not fed into further units. Units whose outputs do feed into other units are called hidden units. Here, h1h_1 and h2h_2 are hidden units and ff is the single output unit.

x₁ x₂ ReLU bias 0 ReLU bias −1 ReLU f bias 0 each input weight is 1 weight 1 weight −2 input hidden layer output
A width-two, one-hidden-layer ReLU network for XOR. The diagram is a picture of three units: two affine-plus-ReLU formulas for the hidden vector, and one more for the output.

On the four possible inputs, s=x1+x2s=x_1+x_2 is 00, 11, or 22, and

f(x1,x2)=ReLU(ReLU(s)2ReLU(s1)).f(x_1,x_2) = \operatorname{ReLU}\bigl( \operatorname{ReLU}(s) - 2\operatorname{ReLU}(s-1) \bigr).

The complete calculation is

(x1,x2)(x_1,x_2)ssh1=ReLU(s)h_1=\operatorname{ReLU}(s)h2=ReLU(s1)h_2=\operatorname{ReLU}(s-1)h12h2h_1-2h_2ff
(0,0)(0,0)0000000000
(1,0)(1,0)1111001111
(0,1)(0,1)1111001111
(1,1)(1,1)2222110000

(The output unit’s ReLU changes nothing here, since h12h2h_1-2h_2 is already nonnegative at all four inputs.)

Building a network with hidden units has changed the expressivity: now we can express XOR.

s 0 1 2 f h₂ switches on: the slope bends slope +1 slope −1
Viewed through s = x₁ + x₂, the XOR network makes the values 0, 1, 0 at s = 0, 1, 2. The hidden unit h₂ = ReLU(s − 1) switches on at s = 1 and changes the slope from +1 to −1. This bend is impossible for a single affine map, whose slope is constant.

A scalar activation ϕ:RR\phi:\mathbb R\to\mathbb R acts on vectors coordinatewise:

ϕ(u1,,un)=(ϕ(u1),,ϕ(un)).\phi(u_1,\ldots,u_n) = (\phi(u_1),\ldots,\phi(u_n)).

Definition 4.3 (feedforward network). A feedforward neural network, or multilayer perceptron (MLP), with layer widths

n0,n1,,nLn_0,n_1,\ldots,n_L

is a map f:Rn0RnLf: \mathbb R^{n_0}\to\mathbb R^{n_L} defined recursively by

h0=x,h_0=\mathbf{x}, a=Wh1+b,h=ϕ(a)(1<L),a_\ell=W_\ell h_{\ell-1}+b_\ell, \qquad h_\ell=\phi_\ell(a_\ell) \quad (1\leq\ell<L),

and

aL=WLhL1+bL,fθ(x)=aL.a_L=W_Lh_{L-1}+b_L, \qquad f_\theta(\mathbf{x})=a_L.

Here WRn×n1W_\ell\in\mathbb R^{n_\ell\times n_{\ell-1}} and a,bRna_\ell,b_\ell\in\mathbb R^{n_\ell} for 1L1\leq\ell\leq L, while hRnh_\ell\in\mathbb R^{n_\ell} for 0<L0\leq\ell<L. Each ϕ:RR\phi_\ell:\mathbb R\to\mathbb R is an activation function applied coordinatewise. The vectors aa_\ell are the preactivations, and the vectors hh_\ell are the activations. When the final output is fed to softmax, its coordinates are the logits.

The parameter θ\theta collects every weight and bias entry. The intermediate vectors h1,,hL1h_1,\ldots,h_{L-1} are the hidden layers; LL is the number of affine layers, or depth, and max<Ln\max_{\ell<L}n_\ell is the width.

A feedforward network fθf_\theta is a deterministic function, not by itself a probabilistic model. When nL=Vn_L=V, softmax gives the associated classifier

P(θ,x)=softmax(fθ(x)).P(\theta,\mathbf{x}) = \operatorname{softmax}(f_\theta(\mathbf{x})).

Some authors count depth differently, for example by counting only hidden layers. Any depth statement should therefore declare its convention. We will care mainly about whether depth grows linearly or stays fixed, so a difference of one is harmless.

input 𝐱 hidden h₁ hidden h₂ logits W₁, b₁ W₂, b₂ W₃, b₃ x₁x₂x₃ z₁z₂z₃
A fully connected feedforward network. Each arrow carries one matrix entry; each non-input node also has a bias. A whole bank of arrows is the matrix multiplication Whℓ−1.

At a hidden unit jj in layer \ell, the node-and-arrow calculation is

(h)j=ϕ(k=1n1(W)jk(h1)k+(b)j).(h_\ell)_j = \phi_\ell \left( \sum_{k=1}^{n_{\ell-1}} (W_\ell)_{jk}(h_{\ell-1})_k + (b_\ell)_j \right).

Writing all units at once gives h=ϕ(Wh1+b)h_\ell=\phi_\ell(W_\ell h_{\ell-1}+b_\ell). The diagram and the matrix formula are two views of exactly the same computation.

In fact, if we use the identity function as the activation, and zero biases, then the fancy diagram above is literally a diagram of matrix multiplication 🙃.

Proposition 4.4 (without nonlinearities, depth collapses). If every activation is the identity map, then a feedforward network is affine, regardless of its depth.

Proof

The composition of two affine maps is affine:

W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2).W_2(W_1\mathbf{x}+b_1)+b_2 = (W_2W_1)\mathbf{x}+(W_2b_1+b_2).

Applying this identity repeatedly collapses all layers to one map

fθ(x)=Weffx+beff.f_\theta(\mathbf{x})=W_{\mathrm{eff}}\mathbf{x}+b_{\mathrm{eff}}.

Here “eff” abbreviates effective: WeffW_{\mathrm{eff}} and beffb_{\mathrm{eff}} are the single weight matrix and bias vector obtained after all the affine layers have been composed.

Thus additional linear layers may change the parametrization, but not the set of functions represented. \square

The nonlinear activation is what allows a network to bend decision boundaries and build new features. Matrix multiplication supplies rich linear mixing; activation functions prevent all of those matrices from collapsing into one.

4.3 Common activation functions

The following plots use the same horizontal scale. Their vertical scales are chosen to show the characteristic shape rather than to compare numerical magnitudes exactly.

step H(t) sigmoid σ(t) tanh tanh(t) ReLU max(0,t) GELU t Φ(t)
Representative activation shapes. The step makes a hard decision; sigmoid and tanh saturate (defined in the table); ReLU is a hinge; GELU is a smooth, slightly non-monotone ReLU-like function.
activationformulastrengths, limitations, and common use
stepH(t)=1{t0}{H(t)=\mathbf1_{\{t\geq0\}}}It is discontinuous and has derivative 00 away from the threshold, so ordinary gradient descent cannot train it effectively.
sigmoidσ(t)=(1+et)1{\sigma(t)=(1+e^{-t})^{-1}}Smooth, bounded. It can saturate: for large t\lvert t\rvert, its derivative is near 00, weakening gradients.
hyperbolic tangenttanht\tanh tSmooth, bounded, centered at 00. Historically common and used in Project Step 3; it also saturates.
ReLUmax{0,t}\max\{0,t\}Cheap, non-saturating on the positive half-line, piecewise linear. It is not differentiable at 00, and a unit stuck on the negative side can receive zero gradient.
GELUtΦ(t)t\Phi(t)A smooth version of ReLU. Common in transformers, used in Project Step 5; it costs more to evaluate than ReLU. Here Φ\Phi denotes the cumulative distribution function of a standard
normal random variable.

Replacing the step function by a smooth or piecewise-linear activation lets a unit retain how far its preactivation lies from zero. Differentiability matters for training (next lecture), although an isolated corner such as ReLU’s at zero is easily handled. For a single unit, changing the activation does not by itself bend the level sets of the preactivation; the nonlinear geometry comes from combining units.

An activation saturates where changing its input has almost no effect on its output, equivalently where its derivative is close to zero. Sigmoid and tanh\tanh saturate in both tails. During backpropagation, derivatives from successive layers are multiplied, so many saturated units can make a gradient very small before it reaches an early layer. ReLU does not saturate on its positive half-line, but on its negative half-line its derivative is zero; a ReLU that remains there on all relevant inputs is sometimes called a dead unit.

Softmax is different from every entry in the table. It acts on a whole vector, not coordinatewise, and its coordinates must interact so that they sum to 11. For this reason it is commonly used in the output (last) layer (where we are trying to classify something), while ReLU, GELU, or tanh\tanh is used in hidden layers.

Consider the example of a neural network classification model for hand-written digits. Perhaps the input values (the original feature vector) are just the darkness of each pixel in a small image file. That’s a design choice. At a hidden layer, one might expect that the activations represent more useful distinguishing features, something like “how dark is the upper half” or “how round is the bottom”. These would be human expectations, however: the model, through training, finds its own best hidden activations, which may not have an easily human-understandable meaning.

You can watch this happen in Adam Harley’s interactive visualization of small networks trained on hand-written digits: draw a digit and see every hidden activation light up, layer by layer. Working out what, if anything, a hidden unit has learned to detect is the research field of interpretability; the Distill article Feature Visualization shows images of the inputs that most excite individual hidden units of an image classifier.

4.4 Neural language models

We can now put the pieces together. A context must first be represented by numbers, a feedforward network turns those numbers into one logit per vocabulary token, and softmax turns the logits into probabilities.

Definition 4.5 (feedforward neural language model). Let V\mathcal V be a vocabulary of size VV. Suppose an encoder

eθ1:VRn0e_{\theta_1}:\mathcal V^*\longrightarrow\mathbb R^{n_0}

represents a context cc by the feature vector eθ1(c)e_{\theta_1}(c). The encoder may be fixed or may have trainable parameters θ1\theta_1. Let

fθ2:Rn0RVf_{\theta_2}:\mathbb R^{n_0}\longrightarrow\mathbb R^V

be a feedforward network. With θ=(θ1,θ2)\theta=(\theta_1,\theta_2), the associated conditional language model is

P(θ,c)=pθ(c)=softmax(fθ2(eθ1(c))).P(\theta,c) = p_\theta(\,\cdot\mid c) = \operatorname{softmax} \left(f_{\theta_2}(e_{\theta_1}(c))\right).

The vector fθ2(eθ1(c))RVf_{\theta_2}(e_{\theta_1}(c))\in\mathbb R^V contains one next-token logit for each vocabulary token.

Example 4.6 (Project Step 2: a hand-wired diamond classifier). Let x=(x1,x2)R2\mathbf{x}=(x_1,x_2)^\top\in\mathbb R^2. The hidden layer

h=ReLU(W1x+b1),W1=(10100101)R4×2,b1=0R4,h=\operatorname{ReLU}(W_1\mathbf{x}+b_1), \qquad W_1= \begin{pmatrix} 1&0\\ -1&0\\ 0&1\\ 0&-1 \end{pmatrix} \in\mathbb R^{4\times2}, \qquad b_1=0\in\mathbb R^4,

has four units:

h=(ReLU(x1)ReLU(x1)ReLU(x2)ReLU(x2)).h= \begin{pmatrix} \operatorname{ReLU}(x_1)\\ \operatorname{ReLU}(-x_1)\\ \operatorname{ReLU}(x_2)\\ \operatorname{ReLU}(-x_2) \end{pmatrix}.

Since ReLU(t)+ReLU(t)=t\operatorname{ReLU}(t)+\operatorname{ReLU}(-t)=|t|, summing these activations produces

r=1h=x1+x2.r=\mathbf1^\top h=|x_1|+|x_2|.

Choose a confidence parameter γ>0\gamma>0 and define two output logits, ordered as “outside” and “inside,” by

z=W2h+b2,W2=γ(11111111)R2×4,b2=γ(11)R2.z=W_2h+b_2, \qquad W_2 = \gamma \begin{pmatrix} 1&1&1&1\\ -1&-1&-1&-1 \end{pmatrix} \in\mathbb R^{2\times4}, \qquad b_2 = \gamma \begin{pmatrix} -1\\ 1 \end{pmatrix} \in\mathbb R^2.

Thus

zout=γ(r1),zin=γ(1r).z_{\mathrm{out}}=\gamma(r-1), \qquad z_{\mathrm{in}}=\gamma(1-r).

With θ=(W1,b1,W2,b2)\theta=(W_1,b_1,W_2,b_2), the classifier is

P(θ,x)=softmax(z).P(\theta,\mathbf{x}) = \operatorname{softmax}(z).

By Aside 3.1a,

pθ(inx)=σ(zinzout)=σ(2γ(1x1x2)).p_\theta(\mathrm{in}\mid\mathbf{x}) = \sigma(z_{\mathrm{in}}-z_{\mathrm{out}}) = \sigma\bigl(2\gamma(1-|x_1|-|x_2|)\bigr).

The two logits are equal exactly when x1+x2=1|x_1|+|x_2|=1. This is a diamond, not a hyperplane. Four hidden units first build the nonlinear feature rr; the output layer then makes an ordinary affine decision in that new feature. Project Step 2 asks you to assemble these units as matrices, inspect their activations, and modify the geometry.

Example 4.7 (Project Step 3: “Bengio-style” neural nn-gram). Let CRV×dC\in\mathbb R^{V\times d} be an embedding matrix, and write Ca,:RdC_{a,:}\in\mathbb R^d for its aath row. The token map

VRd,aCa,:\mathcal V\longrightarrow\mathbb R^d, \qquad a\longmapsto C_{a,:}

turns each token into a feature vector. For a context of n1n-1 tokens (a1,,an1)(a_1,\ldots,a_{n-1}), concatenate those rows:

x=(Ca1,:,,Can1,:)R(n1)d.\mathbf{x} = \bigl(C_{a_1,:},\ldots,C_{a_{n-1},:}\bigr) \in\mathbb R^{(n-1)d}.

A one-hidden-layer network of width hh computes

hctx=tanh(W1x+b1),z=W2hctx+b2.h_{\mathrm{ctx}} = \tanh(W_1\mathbf{x}+b_1), \qquad z=W_2h_{\mathrm{ctx}}+b_2.

For θ=(C,W1,b1,W2,b2)\theta=(C,W_1,b_1,W_2,b_2), the associated language model is

P(θ,(a1,,an1))=pθ(a1,,an1)=softmax(z).P(\theta,(a_1,\ldots,a_{n-1})) = p_\theta(\,\cdot\mid a_1,\ldots,a_{n-1}) = \operatorname{softmax}(z).
tokens rows of C x hidden hctx logits z a₁ a₂ a₃ p(·∣a₁,a₂,a₃) look up in C concatenate tanh(W₁𝐱 + b₁) W₂hctx + b₂ softmax
The neural n-gram of Example 4.7, shown for a context of n − 1 = 3 tokens. Each token selects its row of the embedding matrix C; the rows are concatenated into x ∈ ℝ(n−1)d, which feeds a one-hidden-layer network; softmax turns the V logits into the next-token distribution.

With CRV×dC\in\mathbb R^{V\times d}, W1Rh×(n1)dW_1\in\mathbb R^{h\times (n-1)d}, b1Rhb_1\in\mathbb R^h, W2RV×hW_2\in\mathbb R^{V\times h}, and b2RVb_2\in\mathbb R^V, the parameter count is

Vd+(n1)dh+h+hV+V.Vd+(n-1)dh+h+hV+V.

This grows linearly with context length n1n-1. An unrestricted conditional-probability matrix (that is to say, a basic nn-gram model) would need VnV^{n} entries, exponentially many in nn.


5. Universal approximation

The XOR network is one exact construction. The main result of this section says that such examples are not isolated: even a network with only one hidden layer can approximate every continuous function on a compact set, provided its activation is not a polynomial.

Let KRnK\subset\mathbb R^n be compact, and let C(K)C(K) denote the real-valued continuous functions on KK. For fC(K)f\in C(K), define the uniform norm

f=supxKf(x).\|f\|_\infty = \sup_{\mathbf{x}\in K}|f(\mathbf{x})|.

We use this norm because it controls the worst error anywhere on KK. An average-error norm could hide a large mistake on a small part of the domain; a uniform bound cannot. Compactness ensures that a continuous function is bounded and attains its maximum error, so the displayed quantity is finite.

A family FC(K)\mathcal F\subseteq C(K) is dense in C(K)C(K) under the uniform norm if, for every fC(K)f\in C(K) and every ε>0\varepsilon>0, some gFg\in\mathcal F satisfies

fg<ε.\|f-g\|_\infty<\varepsilon.

Here is the principal theorem.

Theorem 5.1 (universal approximation). Let ϕ:RR\phi:\mathbb R\to\mathbb R be continuous and not a polynomial. For every compact KRnK\subset\mathbb R^n, the one-hidden-layer networks

g(x)=c0+j=1Ncjϕ(wjx+bj),g(\mathbf{x}) = c_0+\sum_{j=1}^N c_j\phi(\mathbf w_j^\top\mathbf{x}+b_j),

where the width NN may vary, are dense in C(K)C(K) under the uniform norm.

ReLU, sigmoid, tanh\tanh, and GELU are all continuous and non-polynomial, so each meets the hypothesis. The theorem permits vector outputs as well: place finitely many scalar networks side by side, one for each output coordinate.

Read the quantifiers carefully. For every target ff and tolerance ε\varepsilon, the theorem promises that some finite width and some parameters exist. It does not give a useful width, construct the parameters, show that gradient descent finds them, or show that finitely many training observations determine the target. In the worst case even an LL-Lipschitz function on [0,1]n[0,1]^n may require resolution on the scale ε/L\varepsilon/L in every coordinate—roughly

(Lε)n\left(\frac{L}{\varepsilon}\right)^n

local regions. Thus existence alone does not make the network economical, trainable, or likely to generalize.

5.1 Examples covered by the theorem

Example 5.2 (absolute value). The absolute-value function is already a tiny ReLU network:

t=ReLU(t)+ReLU(t).|t| = \operatorname{ReLU}(t)+\operatorname{ReLU}(-t).

In the notation of Definition 4.3, its widths are n0=1n_0=1, n1=2n_1=2, and n2=1n_2=1, with

W1=(11),b1=(00),W2=(11),b2=0.W_1= \begin{pmatrix} 1\\-1 \end{pmatrix}, \qquad b_1= \begin{pmatrix} 0\\0 \end{pmatrix}, \qquad W_2= \begin{pmatrix} 1&1 \end{pmatrix}, \qquad b_2=0.

Each hidden ReLU supplies one linear half of the graph.

The same idea constructs every continuous piecewise-linear function on an interval: a ReLU placed at a breakpoint changes the slope from that point onward.

Proposition 5.3 (ReLU approximation on an interval). Let f:[a,b]Rf:[a,b]\to\mathbb R be continuous. For every ε>0\varepsilon>0, there is a one-hidden-layer ReLU network gg such that

supx[a,b]f(x)g(x)<ε.\sup_{x\in[a,b]}|f(x)-g(x)|<\varepsilon.
f q input x error < ε everywhere
A continuous target f (purple) and its polygonal interpolant q (green). A sufficiently fine partition makes the vertical error smaller than ε throughout the interval. Each change of slope in q can be supplied by one hidden ReLU.

The theorem also applies directly to probabilistic models.

Corollary 5.4 (approximating continuous probability maps). Suppose KRnK\subset\mathbb R^n is compact and

p:KrelintΔV1p:K\longrightarrow\operatorname{relint}\Delta^{V-1}

is continuous. For every ε>0\varepsilon>0, a one-hidden-layer network with VV output logits can be chosen so that its softmax output p^(x)\widehat p(\mathbf{x}) satisfies

supxKmax1jVp^j(x)pj(x)<ε.\sup_{\mathbf{x}\in K} \max_{1\leq j\leq V} |\widehat p_j(\mathbf{x})-p_j(\mathbf{x})| < \varepsilon.

Compactness keeps the target uniformly away from the boundary: each continuous coordinate pjp_j has a positive minimum on KK. If a target allows exact zero probabilities, it can first be moved by an arbitrarily small amount toward the uniform distribution.

5.2 Why the theorem is true

We first prove the interval result explicitly.

Proof of Proposition 5.3

A continuous function on a compact interval is uniformly continuous. Choose a partition

a=t0<t1<<tm=ba=t_0<t_1<\cdots<t_m=b

fine enough that f(x)f(y)<ε|f(x)-f(y)|<\varepsilon whenever xx and yy lie in the same subinterval. Let qq be the polygonal interpolant through the points (ti,f(ti))(t_i,f(t_i)). On [ti1,ti][t_{i-1},t_i], the value q(x)q(x) is a convex combination of f(ti1)f(t_{i-1}) and f(ti)f(t_i). Both endpoint values differ from f(x)f(x) by less than ε\varepsilon, so their convex combination does too. Hence fq<ε\|f-q\|_\infty<\varepsilon.

Let

si=f(ti)f(ti1)titi1s_i = \frac{f(t_i)-f(t_{i-1})}{t_i-t_{i-1}}

be the slope of qq on the iith subinterval. For x[a,b]x\in[a,b],

q(x)=f(t0)+s1ReLU(xt0)+j=1m1(sj+1sj)ReLU(xtj).q(x) = f(t_0) + s_1\operatorname{ReLU}(x-t_0) + \sum_{j=1}^{m-1} (s_{j+1}-s_j)\operatorname{ReLU}(x-t_j).

The first ReLU supplies the initial slope; the unit at tjt_j changes that slope by sj+1sjs_{j+1}-s_j. Thus a one-hidden-layer ReLU network realizes qq exactly. \square

For higher-dimensional compact sets there is no equally short polygonal formula. The following outline records the functional-analytic mechanism behind Theorem 5.1; the full projection argument is proved by Leshno, Lin, Pinkus, and Schocken (1993).

Proof outline of Theorem 5.1

A ridge function has the form xϕ(wx+b)\mathbf{x}\mapsto\phi(\mathbf w^\top\mathbf{x}+b): it varies through one scalar projection of x\mathbf{x}. Suppose the closed linear span of all such ridge functions were a proper subspace of C(K)C(K). The Hahn—Banach theorem would give a nonzero continuous linear functional that vanishes on that span. By the Riesz representation theorem, this functional is integration against a nonzero finite signed measure μ\mu on KK. Consequently,

Kϕ(wx+b)dμ(x)=0\int_K \phi(\mathbf w^\top\mathbf{x}+b)\,d\mu(\mathbf{x}) = 0

for every wRn\mathbf w\in\mathbb R^n and bRb\in\mathbb R.

Varying w\mathbf w and bb probes every one-dimensional projection of μ\mu. The projection argument in the cited paper shows that a continuous activation can admit such a nonzero annihilating measure only if it is a polynomial. Since ϕ\phi is not a polynomial, μ\mu must be zero, a contradiction. Therefore the ridge functions have dense linear span.

The non-polynomial condition is essentially necessary for shallow networks. If ϕ\phi is a polynomial of degree mm, every displayed one-hidden-layer sum is a polynomial of degree at most mm. On a compact set with nonempty interior, that fixed finite-dimensional space is not dense in C(K)C(K). \square

Background aside 5.5. Hahn—Banach separates a point from a closed linear subspace by a continuous linear functional. The Riesz representation theorem identifies continuous linear functionals on C(K)C(K) with integration against finite signed measures. These standard results from functional analysis are not prerequisites for using the theorem.

Proof of Corollary 5.4

By Proposition 2.3, the centered logit map

z(x)=logp(x)mean(logp(x))1z(\mathbf{x}) = \log p(\mathbf{x}) - \operatorname{mean}(\log p(\mathbf{x}))\,\mathbf1

is continuous. Approximate each coordinate zjz_j uniformly by a shallow network, and combine all their hidden units into one network with VV outputs. Softmax is uniformly continuous on a compact neighborhood of z(K)z(K), so sufficiently accurate logits give the required uniform probability approximation. \square

Example 5.6 (depth can save width). Universal approximation allows one hidden layer to become arbitrarily wide. A simple family shows that composition can sometimes represent the same function much more efficiently.

Define the triangle map

Δ(t)=2ReLU(t)4ReLU(t12)+2ReLU(t1).\Delta(t) = 2\operatorname{ReLU}(t) - 4\operatorname{ReLU}\left(t-\frac12\right) + 2\operatorname{ReLU}(t-1).

On [0,1][0,1] it rises linearly from 00 to 11 and then falls linearly back to 00. Let fk=Δkf_k=\Delta^{\circ k} be its kk-fold composition.

Δ Δ ∘ Δ Δ ∘ Δ ∘ Δ 0 1 input t
Each composition doubles the number of linear pieces. The height stays fixed while the oscillations become finer.

One copy of Δ\Delta is a width-three ReLU block. Stacking kk copies therefore computes fkf_k exactly with width 33 and depth at most 2k2k. In contrast, suppose a one-hidden-layer ReLU network gg satisfies

fkg<14.\|f_k-g\|_\infty<\frac14.

At the dyadic points j/2kj/2^k, the values of fkf_k alternate between 00 and 11. On each of the 2k12^{k-1} disjoint “teeth,” the two endpoints are near 00 while the midpoint is near 11. No affine function can do that on the whole tooth, because its midpoint value is the average of its endpoint values. Thus gg needs a breakpoint inside every tooth. A width-NN shallow ReLU network has at most NN breakpoints, so necessarily

N2k1.N\geq 2^{k-1}.

This is a depth separation: constant width and depth proportional to kk compete with exponential shallow width. It is an expressivity statement for a specially constructed compositional family. It does not say that every task benefits from depth, or that training will discover the short deep representation.


The preceding results concern representation. They do not settle optimization or generalization, which we separate next.

6. Approximation, optimization, and generalization

Three logically different questions are often compressed into the vague claim that a model “works.”

Distinguishing them requires one piece of vocabulary. The population is modeled as a probability distribution D\mathcal D on input–label pairs (X,Y)(X,Y): an idealized, inexhaustible source of input–label pairs, of which the training set is one finite sample and future data are further samples. A loss (θ;X,Y)\ell(\theta;X,Y) penalizes the model’s prediction on a single pair; a risk is an average of losses over many pairs. Averaging over the whole distribution D\mathcal D gives the population risk (also called the population loss), while averaging over the training sample gives the empirical risk (the training loss). Both are defined precisely below.

questionmathematical formwhat could go wrong
ApproximationDoes some parameter in the model family have small population risk?The architecture may be incapable of representing the target economically.
OptimizationDoes the training algorithm find a parameter with small empirical risk?The objective may be nonconvex, ill-conditioned, noisy, or approached only at infinite norm.
GeneralizationDoes performance on the training sample persist on new data?The fitted model may exploit accidental features or memorize the sample.

To make the distinction precise, let D\mathcal D be the population distribution on input–label pairs (X,Y)(X,Y), and let (θ;X,Y)\ell(\theta;X,Y) be a loss. The population risk is

R(θ)=E(X,Y)D[(θ;X,Y)],R(\theta) = \mathbb E_{(X,Y)\sim\mathcal D} \left[\ell(\theta;X,Y)\right],

whereas the empirical risk on NN training observations is

R^N(θ)=1Ni=1N(θ;xi,yi).\widehat R_N(\theta) = \frac1N\sum_{i=1}^N \ell(\theta;\mathbf{x}_i,y_i).

Let RR^\star denote the best risk attainable without restricting to the chosen model family. Then

infθR(θ)R\inf_\theta R(\theta)-R^\star

is an approximation error. For the output θ^\widehat\theta of a training algorithm,

R^N(θ^)infθR^N(θ)\widehat R_N(\widehat\theta) - \inf_\theta\widehat R_N(\theta)

is an optimization error. The difference R(θ^)R^N(θ^)R(\widehat\theta)-\widehat R_N(\widehat\theta) is one generalization gap.

Adding and subtracting these quantities gives the exact bookkeeping identity

R(θ^)R=infθR(θ)Rapproximation+R^N(θ^)infθR^N(θ)optimization+R(θ^)R^N(θ^)+infθR^N(θ)infθR(θ)estimation/generalization.\begin{aligned} R(\widehat\theta)-R^\star ={}& \underbrace{\inf_\theta R(\theta)-R^\star}_{\text{approximation}}\\ &+ \underbrace{\widehat R_N(\widehat\theta) -\inf_\theta\widehat R_N(\theta)}_{\text{optimization}}\\ &+ \underbrace{R(\widehat\theta)-\widehat R_N(\widehat\theta) +\inf_\theta\widehat R_N(\theta)-\inf_\theta R(\theta)} _{\text{estimation/generalization}}. \end{aligned}

The last line contains two sample-to-population discrepancies. Individual terms can have either sign, but the identity shows where distinct kinds of reasoning enter.

Example 6.1. The ReLU network in Section 4 represents XOR exactly, so its approximation error on the four Boolean inputs can be zero. That fact alone does not show that a particular random initialization and optimizer find the displayed weights. If training data omit (1,1)(1,1), even perfect optimization on the three observed points does not determine the missing label; a fitted network can have zero training error and still fail to generalize.

Remark 6.2 (a theoretical scorecard). Universal approximation and depth separation are rigorous approximation results. Logistic and softmax regression have unusually clean convex optimization theory. Deep-network losses are generally nonconvex. Optimization guarantees exist in special regimes, including some infinite-width neural-tangent-kernel limits, but those regimes do not capture every form of feature learning. Classical VC-dimension and Rademacher-complexity bounds control generalization through the size of a function class, yet can be loose or vacuous for heavily overparametrized networks. Why ordinary gradient methods so often find useful representations that generalize remains only partially understood.


7. The Project Step 2 diamond classifier

Example 4.6 defined the small network used in Project Step 2. We now collect its computation in one place. The point is not to train the network yet, but to see exactly how scalar units become matrix layers and how a hidden layer changes the geometry of a classifier.

Let x=(x1,x2)\mathbf{x}=(x_1,x_2)^\top. The forward pass is

xR2a1=W1x+b1R4h=ReLU(a1)R4z=W2h+b2R2p=softmax(z)Δ1.\mathbf{x}\in\mathbb R^2 \longmapsto a_1=W_1\mathbf{x}+b_1\in\mathbb R^4 \longmapsto h=\operatorname{ReLU}(a_1)\in\mathbb R^4 \longmapsto z=W_2h+b_2\in\mathbb R^2 \longmapsto p=\operatorname{softmax}(z)\in\Delta^1.

The matrices are

W1=(10100101),b1=0,W2=γ(11111111),b2=γ(11),W_1= \begin{pmatrix} 1&0\\ -1&0\\ 0&1\\ 0&-1 \end{pmatrix}, \qquad b_1=0, \qquad W_2 = \gamma \begin{pmatrix} 1&1&1&1\\ -1&-1&-1&-1 \end{pmatrix}, \qquad b_2 = \gamma \begin{pmatrix} -1\\ 1 \end{pmatrix},

where γ>0\gamma>0. The output coordinates are ordered as outside, inside.

Theorem 7.1 (geometry of the diamond network). For the network above,

pθ(inx)=σ(2γ(1x1x2)).p_\theta(\mathrm{in}\mid\mathbf{x}) = \sigma\bigl(2\gamma(1-|x_1|-|x_2|)\bigr).

Consequently:

  1. the two class probabilities are equal exactly on x1+x2=1|x_1|+|x_2|=1;
  2. points with x1+x2<1|x_1|+|x_2|<1 are classified as inside;
  3. points with x1+x2>1|x_1|+|x_2|>1 are classified as outside.

Thus the decision boundary is the diamond with vertices (1,0)(1,0), (0,1)(0,1), (1,0)(-1,0), and (0,1)(0,-1).

Proof

The first affine layer gives

a1=(x1,x1,x2,x2),a_1=(x_1,-x_1,x_2,-x_2)^\top,

so the hidden activation is

h=(ReLU(x1),ReLU(x1),ReLU(x2),ReLU(x2)).h= \bigl( \operatorname{ReLU}(x_1), \operatorname{ReLU}(-x_1), \operatorname{ReLU}(x_2), \operatorname{ReLU}(-x_2) \bigr)^\top.

Therefore

1h=x1+x2=:r.\mathbf1^\top h = |x_1|+|x_2| =:r.

The output logits are zout=γ(r1)z_{\mathrm{out}}=\gamma(r-1) and zin=γ(1r)z_{\mathrm{in}}=\gamma(1-r). Their difference is

zinzout=2γ(1r).z_{\mathrm{in}}-z_{\mathrm{out}} = 2\gamma(1-r).

The two-class softmax identity from Aside 3.1a now gives the probability formula. Since sigmoid is increasing and σ(0)=1/2\sigma(0)=1/2, the three geometric claims follow. \square

x₁ x₂ 1 −1 1 −1 inside outside |x₁| + |x₂| = 1
The Project Step 2 decision boundary. A single logistic-regression unit can draw only one line in this plane. Four hidden ReLUs construct distances from the coordinate axes; their sum produces the four-sided boundary.

For γ=4\gamma=4, a few forward passes are:

| x\mathbf{x} | hidden sum r=x1+x2r=|x_1|+|x_2| | (zout,zin)(z_{\mathrm{out}},z_{\mathrm{in}}) | p(inx)p(\mathrm{in}\mid\mathbf{x}) | |---|---:|---:|---:| | (0,0)(0,0) | 00 | (4,4)(-4,4) | 0.99970.9997 | | (0.5,0.25)(0.5,0.25) | 0.750.75 | (1,1)(-1,1) | 0.88080.8808 | | (1,0)(1,0) | 11 | (0,0)(0,0) | 0.50000.5000 | | (0.8,0.5)(0.8,0.5) | 1.31.3 | (1.2,1.2)(1.2,-1.2) | 0.08320.0832 |

The parameter γ\gamma changes confidence but not the decision boundary. As γ0+\gamma\to0^+, both logits approach zero and the output approaches the uniform distribution. As γ\gamma grows, probabilities approach 11 on the predicted class away from the boundary. This is the two-class version of changing softmax temperature.


Summary

  • Binary logistic regression makes the log-odds an affine function of the features. Sigmoid converts the scalar logit to a Bernoulli probability, and binary cross-entropy is its negative log-likelihood.

  • The logistic-regression gradient is prediction minus target, multiplied by the input. Its loss is convex, and suitably small-step full-batch gradient descent has a global convergence guarantee when a finite minimizer exists.

  • Softmax converts VV logits into a strictly positive categorical distribution. It parametrizes the relative interior of the simplex with one redundant common-shift direction, and logit differences are pairwise log-odds.

  • Multinomial logistic regression is the direct multiclass analogue of binary logistic regression. Its logit gradient is peyp-e_y, and its fixed-feature cross-entropy is convex.

  • A perceptron has one affine boundary and cannot compute XOR. A width-two ReLU hidden layer computes XOR exactly. More generally, nonlinear activations prevent a stack of affine maps from collapsing to one affine map.

  • A continuous non-polynomial activation gives one-hidden-layer universal approximation on compact sets. This establishes existence, not an efficient width, a successful optimization method, or generalization from finite data.

  • Depth can express repeated composition exponentially more efficiently than a shallow network for particular function families. This is a representation theorem, not a claim about every task.

  • Project Step 2 hand-wires a genuine hidden-layer network. Four ReLU units construct x1+x2|x_1|+|x_2|; an affine output layer and softmax turn that feature into a diamond classifier. The parameter γ\gamma changes confidence without changing the boundary.


Exercises (paired with Step 2)

A star marks a Project Step 2 task.

  1. Odds and boundaries. For the delay model in Example 0.3, find the probability, odds, and predicted class at x=(1,1)\mathbf{x}=(-1,1)^\top. Sketch its decision boundary and indicate which side is classified as a delay.

  2. A gradient step by hand. Repeat Example 1.5 with learning rate η=1/2\eta=1/2 and initial values w(0)=0w^{(0)}=0, b(0)=log3b^{(0)}=\log3. Compute all logits, probabilities, gradients, updated parameters, and the loss before and after the step.

  3. Prove directly from (z,y)=log(1+ez)yz\ell(z,y)=\log(1+e^z)-yz that binary logistic loss is convex in zz. Determine when its second derivative is largest.

  4. Trace the diamond network. For each of x=(0,0)\mathbf{x}=(0,0)^\top, (0.5,0.25)(0.5,0.25)^\top, (1,0)(1,0)^\top, and (0.8,0.5)(0.8,0.5)^\top, compute a1a_1, hh, zz, and pp at γ=4\gamma=4. Verify Theorem 7.1 and explain the geometric role of each hidden unit.

  5. Move and stretch the diamond. Construct W1,b1,W2,b2W_1,b_1,W_2,b_2 for a classifier whose boundary is

    x1ar1+x2br2=1,r1,r2>0.\frac{|x_1-a|}{r_1}+\frac{|x_2-b|}{r_2}=1, \qquad r_1,r_2>0.

    State every matrix dimension. Check that your network reduces to the Project Step 2 network when a=b=0a=b=0 and r1=r2=1r_1=r_2=1.

  6. Temperature. For τ>0\tau>0, analyze softmax(z/τ)\operatorname{softmax}(z/\tau). Prove that it tends to the uniform distribution as τ\tau\to\infty and, as τ0+\tau\to0^+, to the uniform distribution on the set of maximizers of zz. Include the unique maximum as a special case.

  7. Perceptrons. Find perceptron weights and biases that compute AND and OR on {0,1}2\{0,1\}^2. Use either the inequalities in Theorem 4.2 or a geometric argument to reprove that XOR is impossible.

  8. A second XOR network. Verify the weights in the XOR diagram by writing its two weight matrices and two bias vectors. Modify only the output affine map to compute XNOR on {0,1}2\{0,1\}^2.

  9. Why activation matters. Derive explicit formulas for WeffW_{\mathrm{eff}} and beffb_{\mathrm{eff}} when three affine layers are composed without activations. Identify the rank constraints imposed by bottleneck widths. Explain why widening those bottlenecks can remove the rank constraints but still cannot introduce nonlinearity.

  10. Prove that a one-hidden-layer ReLU network of width NN on R\mathbb R has at most NN distinct breakpoints and at most N+1N+1 affine pieces. When can it have fewer?

  11. Triangle-map depth. Verify the three-ReLU formula for Δ\Delta. Prove by induction that Δk\Delta^{\circ k} takes alternating values 0,1,0,1,,00,1,0,1,\ldots,0 at j/2kj/2^k and has 2k2^k affine pieces.

  12. Redundancy and regularization. Show that every rowwise softmax equivalence class contains a unique zero-mean logit vector, and that this vector has the smallest Euclidean norm in its class. Then explain why adding λWF2\lambda\|W\|_F^2 does more than choose representatives: it also changes the optimal probability distributions. Compare this shrinkage qualitatively with Laplace smoothing.

  13. From logits to probabilities. Supply the uniform-continuity details in Corollary 5.4. Show also that for a continuous p:KrelintΔV1p:K\to\operatorname{relint}\Delta^{V-1} with compact KK, there is a single δ>0\delta>0 such that pb(x)δp_b(\mathbf{x})\geq\delta for every xx and bb.

  14. Three different failures. Give one small classification example exhibiting each of the following: approximation error despite perfect optimization; optimization error despite a sufficiently expressive model; zero training loss but positive test loss. State clearly which model family, training procedure, and data distribution you use.


Pointers

Bengio, Ducharme, Vincent, and Jauvin, A Neural Probabilistic Language Model (2003); Cybenko (1989); Hornik (1991); Leshno—Lin—Pinkus—Schocken (1993); Pinkus, Approximation Theory of the MLP Model in Neural Networks (1999); Telgarsky, Representation Benefits of Deep Feedforward Networks (2015) and Benefits of Depth in Neural Networks (2016); Higham and Higham, Deep Learning: An Introduction for Applied Mathematicians. See the resources page, Project Step 2, and Project Step 3.