Neural Networks and Optimization

A neural network is a family of functions; training is walking downhill on a loss until one member fits the data. Push numbers through a network by hand, watch width buy accuracy, fit a vector field and follow its flow, steer gradient descent across a narrow valley, sample mini-batches, and see why the small eigenvalues of a quadratic set the speed of learning.

Follows I. Goodfellow, Y. Bengio and A. Courville, Deep Learning (MIT Press, 2016; free online), Chapters 6 and 8, with R. Chen, Y. Rubanova, J. Bettencourt and D. Duvenaud, “Neural ordinary differential equations” (NeurIPS 2018) for the neural-ODE module. The questions and examples are written for this page. A recurring piece of advice on this page: before reading a formula, ask what kind of object each symbol is (a number, a vector, a matrix, a function) and where it lives. For how this subject connects to the others, see the roadmap.

InteractiveGoodfellow–Bengio–Courville, Ch. 6: Deep Feedforward Networks

Neural networks as functions

A neural network is just a family of functions with adjustable weights, and machine learning, at its core, is picking the member of the family that fits the data. The family is built from one simple principle: an affine map followed by a nonlinearity, repeated. (In reinforcement learning, this is how value functions and policies are represented once states are continuous.)

The idea

Learning is function fitting. Given data (xi,yi)(x_i,y_i), find a function ff with f(xi)≈yif(x_i)\approx y_i, then predict f(x)f(x) at inputs you haven't seen. The family of functions you search matters: if it only contains straight lines and the data curve, every prediction will be off.

Feedforward network. Each node takes a weighted sum of every node in the previous layer plus a bias, and applies an activation σ\sigma. In matrix form, one layer is h↦σ(Wh+b)h\mapsto\sigma(Wh+b), and a network with two hidden layers is
fθ(x)=W3σ(W2σ(W1x+b1)+b2)+b3,f_\theta(x)=W_3\,\sigma\big(W_2\,\sigma(W_1x+b_1)+b_2\big)+b_3,
where θ\theta collects every weight matrix and bias vector. The input layer's size is the input dimension (two nodes means x∈ℝ2x\in\R^2); the width is the number of nodes in a hidden layer and the depth is the number of hidden layers.
Without an activation, depth buys nothing. If σ\sigma is the identity, W3(W2(W1x+b1)+b2)+b3=Mx+cW_3(W_2(W_1x+b_1)+b_2)+b_3=Mx+c: a composition of affine maps is affine. However many layers, the network draws a plane.
Universal approximation (Cybenko 1989; Leshno et al. 1993; Goodfellow et al. §6.4.1). With any continuous activation that is not a polynomial, for example ReLU(z)=max⁡(0,z)\mathrm{ReLU}(z)=\max(0,z), one hidden layer suffices: for every continuous gg on a compact set KK and every ε>0\varepsilon>0 there is a network with supx∈K⁡|fθ(x)−g(x)|<ε\sup_{x\in K}|f_\theta(x)-g(x)|<\varepsilon.

The theorem says a good network exists; it does not say how wide it must be, or how to find its weights. Smaller ε\varepsilon generally needs more parameters, and under smoothness assumptions on gg one can say how many. In the figure, a ReLU network with nn hidden units is the piecewise-linear interpolant at n+1n+1 points; for twice-differentiable gg its error falls like 1/n21/n^2.

Explore

Target
Activation
target gg network fθf_\theta. The faint lines are the hidden units' contributions, each a scaled max⁡(0,x−k)\max(0,x-k) with its kink at a knot kk.

Worked example

A network ℝ2→ℝ\R^2\to\R with one hidden layer of two ReLU units: h1=ReLU(x1−2x2+0.1)h_1=\mathrm{ReLU}(x_1-2x_2+0.1), h2=ReLU(−x1+x2)h_2=\mathrm{ReLU}(-x_1+x_2), output y=h1+3h2−1y=h_1+3h_2-1. Evaluate it at x=(1,−1)x=(1,-1) and x=(−1,1)x=(-1,1).

  1. Forward pass at (1,−1)(1,-1).

    h1=ReLU(1+2+0.1)=3.1h_1=\mathrm{ReLU}(1+2+0.1)=3.1, h2=ReLU(−2)=0h_2=\mathrm{ReLU}(-2)=0. y=3.1+0−1=2.1y=3.1+0-1=2.1.

  2. Forward pass at (−1,1)(-1,1).

    h1=ReLU(−1−2+0.1)=0h_1=\mathrm{ReLU}(-1-2+0.1)=0, h2=ReLU(2)=2h_2=\mathrm{ReLU}(2)=2. y=0+6−1=5y=0+6-1=5.

  3. Count the parameters, and say what the network looks like as a function.

    First layer: a 2×22\times2 matrix and 2 biases (6); output: 2 weights and 1 bias (3). Total 9. Each ReLU is zero on one side of a line and linear on the other, so ff is piecewise linear with at most four pieces, cut by the lines x1−2x2+0.1=0x_1-2x_2+0.1=0 and x2=x1x_2=x_1. Large networks are the same thing with far more pieces.

Check your understanding

A network has ten hidden layers of width 100, but no activation functions. It can represent:

  1. Any continuous function, given enough layers.Composing affine maps never leaves the affine maps.
  2. Only affine functions x↦Mx+cx\mapsto Mx+c.
The nonlinearity is what lets layers build on each other. Even the very simple max⁡(0,z)\max(0,z), two linear pieces glued together, is enough for universal approximation.

Universal approximation guarantees that:

  1. Training by gradient descent will find a network within ε\varepsilon of the target.It says nothing about training.
  2. Some network within ε\varepsilon of the target exists, of some size.
  3. A network with a fixed number of units can approximate every continuous function.The size depends on ε\varepsilon and on the target.
Existence, not construction and not size. Rates (how many parameters for a given ε\varepsilon) need extra assumptions on the target, and they are what make bigger models more expressive.

In the figure, the steep step needs many more units than sin for the same error. Why?

  1. Piecewise-linear interpolation error is controlled by the target's slope and curvature, and the step is very steep in one place.
  2. ReLU networks cannot represent increasing functions.Each unit is increasing; sums of them certainly can be.
With knots spaced hh apart, the error is at most h28max⁡|g′′|\tfrac{h^2}8\max|g''|, or h2max⁡|g′|\tfrac h2\max|g'|. Spending knots evenly wastes them on the flat parts; putting them where the function bends is what training (or adaptive knots) does.

Practice

The hat functionThree ReLUs make a bump

Write the hat g(x)=max⁡(0,1−|x|)g(x)=\max(0,1-|x|) as a combination of ReLUs max⁡(0,x−k)\max(0,x-k).

Solution

g(x)=ReLU(x+1)−2ReLU(x)+ReLU(x−1)g(x)=\mathrm{ReLU}(x+1)-2\,\mathrm{ReLU}(x)+\mathrm{ReLU}(x-1). Check: for x≤−1x\le-1 all are 0; on [−1,0][-1,0] it is x+1x+1; on [0,1][0,1] it is x+1−2x=1−xx+1-2x=1-x; for x≥1x\ge1, x+1−2x+x−1=0x+1-2x+x-1=0. Three hidden units. Sums of shifted hats are exactly the piecewise-linear interpolants, which proves universal approximation in one dimension.

Error versus widthA rate

Using nn equally spaced pieces on [−1,1][-1,1], how many hidden units are needed to approximate g(x)=sin⁡(3x)g(x)=\sin(3x) to within 10−310^{-3}?

Solution

h=2/nh=2/n, |g′′|≤9|g''|\le9, so the error is at most (2/n)28⋅9=4.5n2\frac{(2/n)^2}{8}\cdot9=\frac{4.5}{n^2}. Need n2≥4500n^2\ge4500: n≥68n\ge68. Ten times more accuracy costs only about 10≈3.2\sqrt{10}\approx3.2 times more units, because gg is smooth.

InteractiveGoodfellow–Bengio–Courville, §6.1–6.3

The forward pass, layer by layer

Every node does the same small job: take a weighted sum of all the nodes in the layer before, add a bias, and apply the activation. Its output becomes an input to every node in the next layer. Do that layer after layer and the input becomes the output.

The idea

Take two inputs x1,x2x_1,x_2 and a first hidden layer of three nodes. Each node has its own weights and bias:

z1(1)=w11x1+w12x2+b1,z2(1)=w21x1+w22x2+b2,z3(1)=w31x1+w32x2+b3,z^{(1)}_1=w_{11}x_1+w_{12}x_2+b_1,\quad z^{(1)}_2=w_{21}x_1+w_{22}x_2+b_2,\quad z^{(1)}_3=w_{31}x_1+w_{32}x_2+b_3,

and outputs hj(1)=σ(zj(1))h^{(1)}_j=\sigma(z^{(1)}_j). Stacking the weights in a matrix, the whole layer is h(1)=σ(W1x+b1)h^{(1)}=\sigma(W_1x+b_1) with W1W_1 of size 3×23\times2: row jj holds node jj's weights. The next layer takes h(1)h^{(1)} as its input in exactly the same way, and so on.

Reading the shapes. In a network with layer sizes 2→3→3→22\to3\to3\to2: x∈ℝ2x\in\R^2; W1∈ℝ3×2W_1\in\R^{3\times2}, b1∈ℝ3b_1\in\R^3; W2∈ℝ3×3W_2\in\R^{3\times3}, b2∈ℝ3b_2\in\R^3; W3∈ℝ2×3W_3\in\R^{2\times3}, b3∈ℝ2b_3\in\R^2; output y∈ℝ2y\in\R^2. A weight matrix always has shape (nodes in this layer) ×\times (nodes in the previous layer). If the shapes don't fit, the formula is wrong.
Parameters. The weights and biases together, often written θ\theta. This network has (3⋅2+3)+(3⋅3+3)+(2⋅3+2)=29(3\cdot2+3)+(3\cdot3+3)+(2\cdot3+2)=29. When a language model is described by its number of parameters, this is the count being reported (in far larger networks).

Training chooses θ\theta. Once it is chosen, the network is just a fixed function ℝ2→ℝ2\R^2\to\R^2, and evaluating it is the forward pass you can step through below.

Explore

Activation in hidden layers
Click a node to see how its value is computed. Line thickness is the size of the weight; positive negative. A grey node is switched off: ReLU sent its negative sum to 0.

Worked example

The network in the figure has W1=(1−20.51−10.5), b1=(0.10.2−0.4)W_1=\begin{pmatrix}1&-2\\0.5&1\\-1&0.5\end{pmatrix},\ b_1=\begin{pmatrix}0.1\\0.2\\-0.4\end{pmatrix}, W2=(020.51−10.5−0.501), b2=(000.2)W_2=\begin{pmatrix}0&2&0.5\\1&-1&0.5\\-0.5&0&1\end{pmatrix},\ b_2=\begin{pmatrix}0\\0\\0.2\end{pmatrix}, W3=(1−10.50.51−1), b3=(0.1−0.2)W_3=\begin{pmatrix}1&-1&0.5\\0.5&1&-1\end{pmatrix},\ b_3=\begin{pmatrix}0.1\\-0.2\end{pmatrix}, ReLU in the hidden layers and none at the output. Evaluate it at x=(1,−1)x=(1,-1).

  1. First hidden layer: compute z(1)=W1x+b1z^{(1)}=W_1x+b_1, then h(1)h^{(1)}.

    z(1)=(1+2+0.1, 0.5−1+0.2, −1−0.5−0.4)=(3.1,−0.3,−1.9)z^{(1)}=(1+2+0.1,\ 0.5-1+0.2,\ -1-0.5-0.4)=(3.1,\,-0.3,\,-1.9). ReLU zeroes the negatives: h(1)=(3.1,0,0)h^{(1)}=(3.1,0,0).

  2. Second hidden layer.

    z(2)=W2h(1)+b2=(0, 3.1, −1.55+0.2)=(0,3.1,−1.35)z^{(2)}=W_2h^{(1)}+b_2=(0,\ 3.1,\ -1.55+0.2)=(0,3.1,-1.35), so h(2)=(0,3.1,0)h^{(2)}=(0,3.1,0).

  3. Output.

    y=W3h(2)+b3=(−3.1+0.1, 3.1−0.2)=(−3.0, 2.9)y=W_3h^{(2)}+b_3=(-3.1+0.1,\ 3.1-0.2)=(-3.0,\ 2.9). Set the sliders to x=(1,−1)x=(1,-1) and check.

  4. Now remove every activation. What single affine map is the network?

    y=W3(W2(W1x+b1)+b2)+b3=Mx+cy=W_3(W_2(W_1x+b_1)+b_2)+b_3=Mx+c with M=W3W2W1M=W_3W_2W_1 (a 2×22\times2 matrix) and c=W3W2b1+W3b2+b3c=W_3W_2b_1+W_3b_2+b_3. Three layers, 29 parameters, and the result is something 6 parameters already describe.

Check your understanding

A layer maps 128 nodes to 64 nodes. Its weight matrix has shape:

  1. 128×64128\times64It multiplies the previous layer's vector, which has 128 entries, so it needs 128 columns.
  2. 64×12864\times128
W∈ℝ64×128W\in\R^{64\times128} times h∈ℝ128h\in\R^{128} gives ℝ64\R^{64}. Rows are the new nodes, columns the old ones. With the bias, the layer has 64⋅128+64=825664\cdot128+64=8256 parameters.

In the figure, a hidden node is grey for the current input. If you nudge the input slightly, how does that node's output change?

  1. Not at all: it stays at 0 while its sum is negative.
  2. Linearly with the input.Only on the positive side of its kink.
ReLU is flat on the negative side. Which nodes are on or off splits the input space into regions, and on each region the network is a single affine map: a ReLU network is piecewise linear.

Does the bias matter? Without biases, a ReLU network ff always satisfies:

  1. f(0)=0f(0)=0 and f(cx)=cf(x)f(cx)=c\,f(x) for c>0c>0.
  2. Nothing special; biases only shift the output.Try x=0x=0 in every layer.
With no biases each layer is σ(Wh)\sigma(Wh), and ReLU(cz)=cReLU(z)\mathrm{ReLU}(cz)=c\,\mathrm{ReLU}(z) for c>0c>0. So the network can't represent even a constant function unless biases are allowed: the kinks of every unit are stuck at the origin.

Practice

Counting parametersA wider, deeper network

Count the parameters of a network 784→256→256→10784\to256\to256\to10 (an image classifier for 28-by-28 images). Which layer has the most?

Solution

(784⋅256+256)+(256⋅256+256)+(256⋅10+10)=200,960+65,792+2,570=269,322(784\cdot256+256)+(256\cdot256+256)+(256\cdot10+10)=200{,}960+65{,}792+2{,}570=269{,}322. The first layer has three quarters of them: parameter counts are dominated by the widest pair of adjacent layers.

Regions of a ReLU networkOne hidden layer in the plane

A network ℝ2→ℝ\R^2\to\R with one hidden layer of nn ReLU units. Each unit is off on one side of a line. At most how many regions can the nn lines cut the plane into, and what does the network look like on each one?

Solution

nn lines in general position cut the plane into 1+n+(n2)1+n+\binom n2 regions. On each region every unit is either off or exactly linear, so the network is affine there: a piecewise-linear surface with up to 1+n+n(n−1)/21+n+n(n-1)/2 flat pieces. Depth multiplies the count further, which is one explanation of why deep networks are more expressive than shallow ones of the same size.

InteractiveChen et al. (2018), Neural Ordinary Differential Equations

Neural ODEs: learning a flow

Usually you are given a differential equation and asked for its solutions. Turn it around: you are given solutions (observed trajectories of some system) and asked for the equation. A neural ODE answers with a neural network for the velocity, one network for every starting point.

The idea

The system. An ordinary differential equation z˙(t)=F(z(t),t)\dot z(t)=F\big(z(t),t\big), z(0)=z0z(0)=z_0, with z(t)∈ℝdz(t)\in\R^d. Written out, it is a system of dd equations z˙i=Fi(z1,…,zd,t)\dot z_i=F_i(z_1,\dots,z_d,t), each with a single derivative, in time. (A partial differential equation, like the heat equation ∂tu=∂x2u\partial_tu=\partial_x^2u, mixes derivatives in several variables; that is the difference.) FF is the vector field: at each point and time, the velocity.

Examples. z˙=t\dot z=t integrates directly: z(t)=z0+t2/2z(t)=z_0+t^2/2. For z˙=−z\dot z=-z, separate the variables: dzz=−dt\frac{dz}z=-dt, so log⁡|z|=−t+c\log|z|=-t+c and z(t)=z0e−tz(t)=z_0e^{-t}. In general one can write z(t)=z0+∫0tF(z(s),s)dsz(t)=z_0+\int_0^tF(z(s),s)\,ds, but that is circular as a recipe: the unknown zz is inside the integral.

The flow map. Fix a time TT. The map φT:ℝd→ℝd\varphi_T:\R^d\to\R^d, z0↦z(T)z_0\mapsto z(T), sends each starting point to where its solution is at time TT. Check what kind of object it is: a vector goes in and a vector comes out. It is not a curve; the curves appear when you let TT vary, and the family of all φt\varphi_t is the flow.
Neural ODE. Replace the unknown FF by a network Fθ(z,t)F_\theta(z,t), solve x˙=Fθ(x,t)\dot x=F_\theta(x,t), x(0)=z0x(0)=z_0, and choose θ\theta so that the solutions xz0(t)x_{z_0}(t) match the observed ones. The same θ\theta is used for every starting point: the goal is the law of motion, not a separate fit per trajectory.
What “approximate the flow” means. For a compact (closed and bounded) set KK of starting points and a finite horizon TT, universal-approximation results for neural ODEs give, for every ε>0\varepsilon>0, parameters θ\theta with
supz0∈K⁡ supt∈[0,T]⁡ |zz0(t)−xz0(t)|<ε.\sup_{z_0\in K}\ \sup_{t\in[0,T]}\ \big|z_{z_0}(t)-x_{z_0}(t)\big|<\varepsilon.
One network, every starting point in KK, every time up to TT. The error goes to 0 as the number of parameters grows; with more smoothness of FF, one can say how fast.

Sup, not max. sup⁡\sup is the least upper bound, which always exists for a bounded set of real numbers; a maximum need not. On (0,1)(0,1), f(x)=xf(x)=x has supremum 1 but no maximum, since 1 is never reached. When a maximum exists the two agree, so writing sup⁡\sup is simply the safe choice.

Variants. The network can take time as an input in different ways: weights that are functions of time (or piecewise constant in time), or, in semi-autonomous neural ODEs, one fixed set of weights with time entering only linearly inside the activation, Fθ(z,t)=Wσ(A1z+a2t+b)F_\theta(z,t)=W\sigma(A_1z+a_2t+b). Check the shapes: A1A_1 is square, zz, a2a_2, bb are column vectors and tt is a scalar, so A1z+a2t+bA_1z+a_2t+b is a column vector. Setting a2=0a_2=0 gives an autonomous field, one that does not depend on time.

Explore

Show
A damped pendulum, z˙1=z2, z˙2=−sin⁡z1−0.3z2\dot z_1=z_2,\ \dot z_2=-\sin z_1-0.3z_2. Drag the ring KK of starting points. true trajectories trajectories of the fitted network Fθ(z)=Wtanh⁡(Az+b)F_\theta(z)=W\tanh(Az+b), with nn hidden units fitted to the true field on the grey box.

Worked example

Why the theorem needs a compact set and a finite horizon.

  1. Solve z˙=z2\dot z=z^2, z(0)=z0>0z(0)=z_0>0. What happens?

    Separate: dz/z2=dtdz/z^2=dt, so −1/z=t−1/z0-1/z=t-1/z_0 and z(t)=z01−z0tz(t)=\dfrac{z_0}{1-z_0t}. It blows up at t=1/z0t=1/z_0. On [0,T][0,T] with T≥1/z0T\ge1/z_0 there is no solution to approximate.

  2. Take K=[0.1,0.5]K=[0.1,0.5] and T=1T=1. Does every solution exist on [0,T][0,T], and how large does it get?

    Yes: blow-up happens at 1/z0≥2>11/z_0\ge2>1. The largest value is z(1)=0.5/(1−0.5)=1z(1)=0.5/(1-0.5)=1 from z0=0.5z_0=0.5. Everything stays in the compact interval [0.1,1][0.1,1], which is where the network needs to be accurate.

  3. Why can't one network work for all z0∈(0,∞)z_0\in(0,\infty) and all tt?

    Solutions from large z0z_0 leave every bounded set almost immediately, and a network with finitely many units is approximately linear far from the data (or bounded, with tanh), so it can't track z2z^2 everywhere. Restricting to a compact KK and finite TT keeps all the trajectories inside one bounded region. In the figure, drag KK far out or raise TT and watch the error grow.

Check your understanding

The flow map φT\varphi_T for a system in ℝd\R^d is a function from:

  1. ℝd\R^d to curves in ℝd\R^d.That is what you get when TT is allowed to vary.
  2. ℝd\R^d to ℝd\R^d: starting point to position at time TT.
  3. ℝ\R to ℝd\R^d.That describes one trajectory t↦z(t)t\mapsto z(t), with z0z_0 fixed.
Fix TT and vary z0z_0: a map from vectors to vectors. Fix z0z_0 and vary tt: a curve. Asking “what kind of object is this?” sorts out most confusion in a paper.

Why train one network for all starting points rather than one network per trajectory?

  1. One network approximates the law of motion FF, which predicts trajectories from starting points never observed.
  2. It is cheaper to train.Maybe, but the real reason is what you learn.
Three separate fits would memorize three curves and say nothing about a fourth starting point. A single vector field is a model of the system.

In the figure, the trajectories of the fitted field drift away from the true ones as TT grows, even with a good fit. Why?

  1. Small errors in the velocity accumulate along the trajectory and can grow over time.
  2. The numerical solver loses accuracy after a while.The same solver is used for both fields.
By Grönwall's inequality, if |F−Fθ|≤δ|F-F_\theta|\le\delta and FF is LL-Lipschitz, trajectories differ by at most δ(eLT−1)/L\delta\,(e^{LT}-1)/L: the bound grows exponentially in TT. That is why approximation results fix a finite horizon.

Practice

A linear flowFlow maps compose

For z˙=Az\dot z=Az with A∈ℝd×dA\in\R^{d\times d} constant, find φt\varphi_t and show φs+t=φs∘φt\varphi_{s+t}=\varphi_s\circ\varphi_t.

Solution

z(t)=etAz0z(t)=e^{tA}z_0, so φt\varphi_t is multiplication by the matrix etAe^{tA}, and e(s+t)A=esAetAe^{(s+t)A}=e^{sA}e^{tA}. Flowing for tt and then for ss is flowing for s+ts+t. This holds for any autonomous field; with a time-dependent FF the maps depend on the start time too.

Grönwall in one lineHow errors grow

Let z˙=F(z)\dot z=F(z) and x˙=G(x)\dot x=G(x) with x(0)=z(0)x(0)=z(0), |F−G|≤δ|F-G|\le\delta everywhere and FF LL-Lipschitz. Show |z(t)−x(t)|≤δL(eLt−1)|z(t)-x(t)|\le\frac\delta L(e^{Lt}-1).

Solution

e(t)=|z(t)−x(t)|e(t)=|z(t)-x(t)| satisfies e(t)≤∫0t|F(z)−F(x)|+|F(x)−G(x)|ds≤∫0t(Le(s)+δ)dse(t)\le\int_0^t|F(z)-F(x)|+|F(x)-G(x)|\,ds\le\int_0^t(Le(s)+\delta)\,ds. Grönwall's lemma gives e(t)≤δte(t)\le\delta t when L=0L=0 and δL(eLt−1)\frac\delta L(e^{Lt}-1) in general. So a velocity error of δ\delta costs at most δTeLT\delta\,T\,e^{LT} on [0,T][0,T], which is why controlling the sup error of the field controls the sup error of the flow on a finite horizon.

InteractiveGoodfellow–Bengio–Courville, Ch. 8: Optimization for Training Deep Models

Gradient descent, momentum and mini-batches

Fitting a network means minimizing a loss over its weights. Gradient descent does it by walking downhill: from wherever you are, take a small step in the direction in which the loss decreases fastest.

The idea

Why the negative gradient? The rate of change of LL in a unit direction vv is the directional derivative ∇L⋅v=‖∇L‖‖v‖cos⁡ϕ\nabla L\cdot v=\|\nabla L\|\,\|v\|\cos\phi, where ϕ\phi is the angle between them. It is most negative when cos⁡ϕ=−1\cos\phi=-1, that is, when vv points opposite to ∇L\nabla L. So

wt+1=wt−α∇L(wt).w_{t+1}=w_t-\alpha\,\nabla L(w_t).

The gradient says which way to go, not how far: the learning rate α\alpha is a choice. In machine learning L(θ)=1N∑i=1Nℓ(fθ(xi),yi)L(\theta)=\frac1N\sum_{i=1}^N\ell\big(f_\theta(x_i),y_i\big) is the average loss over the data, and computing its gradient through the network's layers is backpropagation.

Quadratics, one direction at a time. For L(w)=12(w−w⋆)⊤H(w−w⋆)L(w)=\tfrac12(w-w^\star)^\top H(w-w^\star) with HH symmetric positive definite, ∇L=H(w−w⋆)\nabla L=H(w-w^\star), so
wt+1−w⋆=(I−αH)(wt−w⋆).w_{t+1}-w^\star=(I-\alpha H)(w_t-w^\star).
Along an eigenvector of HH with eigenvalue λ\lambda, the error is multiplied by 1−αλ1-\alpha\lambda each step. Steep directions (large λ\lambda) need α<2/λmax⁡\alpha<2/\lambda_{\max} or the iterates blow up; flat directions (small λ\lambda) then crawl at rate 1−αλmin⁡1-\alpha\lambda_{\min}. The ratio κ=λmax⁡/λmin⁡\kappa=\lambda_{\max}/\lambda_{\min} sets the speed: about κ\kappa steps per factor of ee.
Momentum (heavy ball). Keep part of the previous step:
wt+1=wt−α∇L(wt)+β(wt−wt−1).w_{t+1}=w_t-\alpha\nabla L(w_t)+\beta\,(w_t-w_{t-1}).
In a flat valley the steps all point the same way and add up; across a narrow valley they alternate and cancel. Well tuned, it needs about κ\sqrt\kappa steps instead of κ\kappa.
Mini-batches. With millions of data points, use the average gradient over a random batch BtB_t of |B||B| of them: gt=1|B|∑i∈Bt∇ℓig_t=\frac1{|B|}\sum_{i\in B_t}\nabla\ell_i. It is unbiased, 𝔼[gt]=∇L\mathbb E[g_t]=\nabla L, but noisy, with variance shrinking like 1/|B|1/|B|. The noise is the price of cheap steps, and it keeps the iterates jittering near the minimum unless α\alpha is decreased.

Explore

Contours of L(w)=12(w12+κw22)L(w)=\tfrac12(w_1^2+\kappa w_2^2); the minimum is at the centre. Drag the start. the first 60 steps.

Worked example

L(w)=12(w12+10w22)L(w)=\tfrac12(w_1^2+10w_2^2), so H=diag(1,10)H=\mathrm{diag}(1,10). Start at w0=(1,1)w_0=(1,1).

  1. With α=0.1\alpha=0.1: the per-step factors in each coordinate, and wtw_t.

    1−0.1⋅1=0.91-0.1\cdot1=0.9 and 1−0.1⋅10=01-0.1\cdot10=0. So w1=(0.9,0)w_1=(0.9,0): the steep coordinate is solved in one step, and wt=(0.9t,0)w_t=(0.9^t,0) after that. Reaching |w1|<10−3|w_1|<10^{-3} takes t≥66t\ge66 steps.

  2. With α=0.25\alpha=0.25?

    Factors 0.750.75 and 1−2.5=−1.51-2.5=-1.5. The second coordinate flips sign and grows by 1.5 each step: divergence, since α>2/λmax⁡=0.2\alpha>2/\lambda_{\max}=0.2.

  3. What is the best fixed α\alpha, and how fast is it?

    Balance the two factors: 1−α=−(1−10α)1-\alpha=-(1-10\alpha), so α=2/11\alpha=2/11 and both have size 9/11=κ−1κ+1≈0.829/11=\frac{\kappa-1}{\kappa+1}\approx0.82. About 35 steps for three digits. Momentum improves this to roughly κ−1κ+1≈0.52\frac{\sqrt\kappa-1}{\sqrt\kappa+1}\approx0.52 per step.

Check your understanding

Why step against the gradient rather than along it?

  1. ∇L⋅v=‖∇L‖‖v‖cos⁡ϕ\nabla L\cdot v=\|\nabla L\|\|v\|\cos\phi is smallest at ϕ=π\phi=\pi: the loss falls fastest opposite to the gradient.
  2. Along the gradient the step would be too long.Length is set by α\alpha; direction is the issue.
The gradient points uphill, in the direction of fastest increase. Gradient ascent (+α∇L+\alpha\nabla L) maximizes, as in policy-gradient methods that maximize expected return.

On an ill-conditioned quadratic (κ=100\kappa=100) plain gradient descent is slow because:

  1. α\alpha must be below 2/λmax⁡2/\lambda_{\max} for the steep direction, which makes progress in the flat direction tiny.
  2. The gradient points away from the minimum.It points downhill, just not at the minimum: it zigzags across the valley.
One learning rate serves all directions. Momentum, preconditioning and adaptive methods (Adam) are different ways around this.

Doubling the batch size |B||B| changes the mini-batch gradient's standard deviation by a factor of:

  1. 1/21/2That is the variance, not the standard deviation.
  2. 1/21/\sqrt2
  3. 11: the noise comes from the data, not the batch.Averaging more independent samples reduces it.
The average of |B||B| independent gradients has variance σ2/|B|\sigma^2/|B|. Twice the work per step buys only 2\sqrt2 less noise, which is one reason small batches are popular.

Practice

The gradient of a quadraticThree lines

For L(w)=12w⊤Hw−q⊤wL(w)=\tfrac12w^\top Hw-q^\top w with HH symmetric, show ∇L=Hw−q\nabla L=Hw-q, find the minimizer, and rewrite gradient descent as wt+1−w⋆=(I−αH)(wt−w⋆)w_{t+1}-w^\star=(I-\alpha H)(w_t-w^\star).

Solution

∂k12∑ijHijwiwj=12∑j(Hkj+Hjk)wj=(Hw)k\partial_k\tfrac12\sum_{ij}H_{ij}w_iw_j=\tfrac12\sum_j(H_{kj}+H_{jk})w_j=(Hw)_k by symmetry, and ∂kq⊤w=qk\partial_kq^\top w=q_k. The minimizer solves Hw⋆=qHw^\star=q. Then wt+1=wt−α(Hwt−q)=wt−αH(wt−w⋆)w_{t+1}=w_t-\alpha(Hw_t-q)=w_t-\alpha H(w_t-w^\star); subtract w⋆w^\star.

Momentum on a lineThe characteristic equation

Apply heavy ball to L(w)=λ2w2L(w)=\tfrac\lambda2w^2. Show that et=wte_t=w_t satisfies et+1=(1+β−αλ)et−βet−1e_{t+1}=(1+\beta-\alpha\lambda)e_t-\beta e_{t-1}, and find when it converges for β=0.5\beta=0.5, λ=1\lambda=1.

Solution

Substitute ∇L=λw\nabla L=\lambda w. The roots of z2−(1+β−αλ)z+β=0z^2-(1+\beta-\alpha\lambda)z+\beta=0 have product β=0.5\beta=0.5; the iteration converges iff both have modulus below 1, which (Jury's test) means |1+β−αλ|<1+β|1+\beta-\alpha\lambda|<1+\beta: 0<α<30<\alpha<3. Momentum enlarges the stable range from α<2\alpha<2 to α<2(1+β)\alpha<2(1+\beta).

InteractiveGoodfellow–Bengio–Courville, §8.1.3 and §8.3.1

Mini-batches and stochastic gradients

The loss is an average over the whole dataset, and so is its gradient. With millions of data points, computing it exactly for every step is too expensive. Instead, pick a small random batch, average its gradients, and step. The step is now random, and that randomness is the whole story of this module.

The idea

With data (xi,yi)(x_i,y_i), i=1,…,Ni=1,\dots,N, and a per-example loss ℓi(θ)=ℓ(fθ(xi),yi)\ell_i(\theta)=\ell(f_\theta(x_i),y_i),

L(θ)=1N∑i=1Nℓi(θ),∇L(θ)=1N∑i=1N∇ℓi(θ).L(\theta)=\frac1N\sum_{i=1}^N\ell_i(\theta),\qquad\nabla L(\theta)=\frac1N\sum_{i=1}^N\nabla\ell_i(\theta).

One full gradient step costs NN per-example gradients.

Mini-batch SGD. At step tt, draw a batch BtB_t of |B||B| indices uniformly at random and step along
gt=1|B|∑i∈Bt∇ℓi(θt),θt+1=θt−αgt.g_t=\frac1{|B|}\sum_{i\in B_t}\nabla\ell_i(\theta_t),\qquad\theta_{t+1}=\theta_t-\alpha\,g_t.
Each step costs |B||B| gradients instead of NN.
Why it works, and what it costs. Where does the randomness come from? Only from which examples were picked; a different batch gives a different step. Averaged over the possible batches, 𝔼[gt]=∇L(θt)\mathbb E[g_t]=\nabla L(\theta_t): the step is right on average (unbiased). Its variance is σ2|B|\frac{\sigma^2}{|B|} when sampling with replacement, where σ2\sigma^2 is the variance of a single example's gradient (without replacement, multiply by N−|B|N−1\frac{N-|B|}{N-1}). So the noise shrinks like 1/|B|1/\sqrt{|B|} while the cost grows like |B||B|.

The consequence: with a fixed step size α\alpha, SGD does not converge to the minimizer. It reaches the neighbourhood quickly and then jitters around it, at a scale set by α\alpha and the noise. Decreasing α\alpha over time (a schedule) or increasing |B||B| shrinks the jitter.

Explore

100 data points. this step's batch and the current line y=ax+cy=ax+c.
Loss over (a,c)(a,c). full gradient descent mini-batch SGD minimizer.

Worked example

Fit fθ(x)=θxf_\theta(x)=\theta x to four points x=(1,2,3,4)x=(1,2,3,4), y=(2,3,7,8)y=(2,3,7,8) with ℓi=12(θxi−yi)2\ell_i=\tfrac12(\theta x_i-y_i)^2. Take θ=1\theta=1.

  1. Compute each ∇ℓi=(θxi−yi)xi\nabla\ell_i=(\theta x_i-y_i)x_i and the full gradient.

    Residuals θxi−yi=(−1,−1,−4,−4)\theta x_i-y_i=(-1,-1,-4,-4); gradients (−1,−2,−12,−16)(-1,-2,-12,-16). Full gradient −31/4=−7.75-31/4=-7.75.

  2. List the mini-batch gradients for all six batches of size 2.

    {1,2}:−1.5\{1,2\}:-1.5, {1,3}:−6.5\{1,3\}:-6.5, {1,4}:−8.5\{1,4\}:-8.5, {2,3}:−7\{2,3\}:-7, {2,4}:−9\{2,4\}:-9, {3,4}:−14\{3,4\}:-14. They range from −1.5-1.5 to −14-14.

  3. Average them.

    −46.5/6=−7.75-46.5/6=-7.75, the full gradient exactly. Unbiased, but any single step can be five times too short or nearly twice too long.

Check your understanding

The randomness in a mini-batch gradient comes from:

  1. Noise in the labels yiy_i.The data are fixed once collected; full-batch descent on them is deterministic.
  2. Which examples happened to be drawn into the batch.
  3. Rounding errors.Those are tiny and not the point.
Whenever a quantity is random, ask what it depends on. Here the only random input is the choice of indices, made to avoid computing all NN gradients.

You quadruple the batch size. Per step, the gradient's standard deviation:

  1. halves, and each step costs four times as much.
  2. quarters, at four times the cost.That's the variance.
Standard deviation σ/|B|\sigma/\sqrt{|B|}. Diminishing returns: past some batch size, more examples per step buy little extra accuracy per unit of compute.

In the figure, with |B|=1|B|=1 and a large step, the SGD path ends in a cloud around the minimizer rather than at it. To land closer you could:

  1. Decrease the step size over time, or use bigger batches.
  2. Run more steps with the same settings.The cloud has a fixed size for fixed α and |B|: more steps just wander inside it.
With step α\alpha and noise variance σ2/|B|\sigma^2/|B|, the stationary jitter has size of order ασ2/|B|\sqrt{\alpha\sigma^2/|B|}. Robbins–Monro step sizes (∑αt=∞\sum\alpha_t=\infty, ∑αt2<∞\sum\alpha_t^2<\infty) drive it to zero.

Practice

UnbiasednessProve it

Let BB be |B||B| indices drawn independently and uniformly from {1,…,N}\{1,\dots,N\}. Show 𝔼[g]=∇L\mathbb E[g]=\nabla L and Var(g)=σ2/|B|\mathrm{Var}(g)=\sigma^2/|B| (coordinatewise), where σ2=1N∑i|∇ℓi−∇L|2\sigma^2=\frac1N\sum_i|\nabla\ell_i-\nabla L|^2 is computed per coordinate.

Solution

Each draw II has 𝔼[∇ℓI]=1N∑i∇ℓi=∇L\mathbb E[\nabla\ell_I]=\frac1N\sum_i\nabla\ell_i=\nabla L and variance σ2\sigma^2. gg is the average of |B||B| independent copies: same mean, variance divided by |B||B|.

EpochsCounting passes

With N=50,000N=50{,}000 examples and |B|=100|B|=100, how many SGD steps make one pass over the data (an epoch)? How many full-gradient steps cost the same?

Solution

500 SGD steps per epoch; the same compute buys one full-gradient step. Early in training, 500 noisy steps make far more progress than one exact one, which is why mini-batches are standard.

SimulationGoodfellow–Bengio–Courville, §8.2 and §8.3.2

Quadratics, spectra and power laws

On a quadratic loss, gradient descent splits into independent one-dimensional problems, one for each eigenvector of the Hessian. Each shrinks at its own rate, and the slow ones, with small eigenvalues, set the pace. When the eigenvalues follow a power law, so does the loss: Lt≈t−ζL_t\approx t^{-\zeta}.

The idea

The model. L(w)=12w⊤Hw−q⊤wL(w)=\tfrac12w^\top Hw-q^\top w. Check the objects: w,qw,q are column vectors, HH is a symmetric matrix, so w⊤Hww^\top Hw and q⊤wq^\top w are numbers and LL is a number. The gradient with respect to ww (the variable we choose; HH and qq are given) is Hw−qHw-q, so the minimizer has Hw⋆=qHw^\star=q.

Where HH comes from. For a linear model with squared loss, ℓ=12(⟨w,x⟩−y)2\ell=\tfrac12(\langle w,x\rangle-y)^2 averaged over data, the Hessian is H=𝔼[xx⊤]H=\mathbb E[xx^\top]. Note the order: x⊤xx^\top x is a number (inner product), xx⊤xx^\top is a matrix (outer product). HH is the covariance of the inputs, so its eigenvalues measure how much the data vary in each direction.

Spectral decomposition. Write H=∑kλkukuk⊤H=\sum_k\lambda_ku_ku_k^\top with orthonormal eigenvectors uku_k. “Decomposing” the error vector et=wt−w⋆e_t=w_t-w^\star means writing it in this basis, et=∑kck(t)uke_t=\sum_kc_k(t)u_k. Since et+1=(I−αH)ete_{t+1}=(I-\alpha H)e_t,
ck(t)=(1−αλk)tck(0),L(wt)−L(w⋆)=12∑kλk(1−αλk)2tck(0)2.c_k(t)=(1-\alpha\lambda_k)^t\,c_k(0),\qquad L(w_t)-L(w^\star)=\tfrac12\sum_k\lambda_k(1-\alpha\lambda_k)^{2t}c_k(0)^2.
Directions with αλk\alpha\lambda_k near 1 are fixed in a step or two; directions with tiny λk\lambda_k barely move.
Power laws. Suppose the error mass in small eigen-directions follows a power law: ∑k:λk≤λλkck(0)2≈λζ\sum_{k:\lambda_k\le\lambda}\lambda_kc_k(0)^2\approx\lambda^{\zeta} for small λ\lambda, with an exponent ζ>0\zeta>0 that is a property of the problem, not something you choose. Since (1−αλ)2t≈e−2αλt(1-\alpha\lambda)^{2t}\approx e^{-2\alpha\lambda t} is near 0 when λ≫1/(αt)\lambda\gg1/(\alpha t) and near 1 when λ≪1/(αt)\lambda\ll1/(\alpha t), after tt steps only the directions with λ≲1/(αt)\lambda\lesssim1/(\alpha t) remain:
L(wt)−L(w⋆)≈12∑k:λk≲1/(αt)λkck(0)2≈(αt)−ζ.L(w_t)-L(w^\star)\approx\tfrac12\sum_{k:\lambda_k\lesssim1/(\alpha t)}\lambda_kc_k(0)^2\approx(\alpha t)^{-\zeta}.
Larger ζ\zeta means less error hides in the flat directions, and faster learning. Power-law spectra like this are what is observed for real data and kernels, which is one reason training losses often fall like a power of the step count.

Momentum and acceleration. With constant α\alpha and β\beta, heavy ball behaves like gradient descent with step α/(1−β)\alpha/(1-\beta) on the slow directions: a constant-factor gain, the same exponent ζ\zeta. Schedules that vary αt,βt\alpha_t,\beta_t with tt (built from orthogonal polynomials such as Chebyshev or Jacobi polynomials) can roughly double the exponent to t−2ζt^{-2\zeta} on deterministic problems. With mini-batch noise these aggressive schedules can amplify the noise and diverge, which is an active research question.

Polynomials and contours. After tt steps of any such method the error is et=pt(H)e0e_t=p_t(H)e_0 for a polynomial ptp_t of degree tt with pt(0)=1p_t(0)=1 (for gradient descent, pt(λ)=(1−αλ)tp_t(\lambda)=(1-\alpha\lambda)^t). So the question “how fast can a method be?” becomes “how small can such a polynomial be on the spectrum?”. Functions of a matrix can be written with Cauchy's integral formula: for a closed curve Γ\Gamma in the complex plane enclosing all the eigenvalues,

f(H)=12πi∮Γf(z)(zI−H)−1dz,f(H)=\frac1{2\pi i}\oint_\Gamma f(z)\,(zI-H)^{-1}\,dz,
which for diagonalizable HH is the scalar formula f(λ)=12πi∮Γf(z)z−λdzf(\lambda)=\frac1{2\pi i}\oint_\Gamma\frac{f(z)}{z-\lambda}dz applied to each eigenvalue. Some recent work designs optimizers by choosing the contour Γ\Gamma instead of the polynomial, and complex numbers are natural there: the per-direction iteration of a momentum method is a 2×22\times2 matrix whose eigenvalues are complex when it oscillates.

Explore

A quadratic with 20,000 eigen-directions, λk=k−ν\lambda_k=k^{-\nu}, step α=1\alpha=1. Log–log axes. gradient descent heavy ball (constant β) slope −ζ-\zeta for reference.

Worked example

H=diag(1,0.01)H=\mathrm{diag}(1,\,0.01), w⋆=0w^\star=0, w0=(1,1)w_0=(1,1), step α=1\alpha=1.

  1. Per-step factors and wtw_t.

    1−αλ1=01-\alpha\lambda_1=0 and 1−αλ2=0.991-\alpha\lambda_2=0.99: w1=(0,0.99)w_1=(0,0.99), then wt=(0,0.99t)w_t=(0,0.99^t). The first direction is solved immediately.

  2. The loss, and how many steps to reduce it by a factor of 1000.

    Lt=12⋅0.01⋅0.992tL_t=\tfrac12\cdot0.01\cdot0.99^{2t}. Need 0.992t≤10−30.99^{2t}\le10^{-3}: t≥ln⁡10002ln⁡(1/0.99)≈344t\ge\frac{\ln1000}{2\ln(1/0.99)}\approx344. All of that time is spent on the flat direction.

  3. Could a larger step help?

    Only up to α<2/λmax⁡=2\alpha<2/\lambda_{\max}=2, where the steep factor is |1−α||1-\alpha|. At α=1.98\alpha=1.98 the flat factor is 0.98020.9802, about 175 steps, but the steep direction now oscillates with factor 0.980.98. The best fixed step balances the two at α=2/1.01\alpha=2/1.01, giving κ−1κ+1≈0.980\frac{\kappa-1}{\kappa+1}\approx0.980 for κ=100\kappa=100. With thousands of directions spread over many scales, there is no balancing point, and the power law takes over.

Check your understanding

For a column vector x∈ℝdx\in\R^d, the object xx⊤xx^\top is:

  1. The number |x|2|x|^2.That is x⊤xx^\top x.
  2. A d×dd\times d matrix of rank one.
A column times a row is a matrix (outer product); a row times a column is a number (inner product). Averaging the rank-one matrices xixi⊤x_ix_i^\top over the data gives the Hessian of the squared loss for a linear model.

“Spectral decomposition of the error vector ete_t” means:

  1. Computing the eigenvalues of ete_t.A vector has no eigenvalues; the spectrum is HH's.
  2. Writing ete_t as a combination of the eigenvectors of HH.
The spectrum belongs to the matrix. Decomposing a vector along it gives coordinates ckc_k, each of which gradient descent multiplies by its own factor 1−αλk1-\alpha\lambda_k.

In the figure, raising the momentum β\beta from 0 to 0.9 shifts the heavy-ball curve but leaves its slope at about −ζ-\zeta. Why?

  1. With constant α,β\alpha,\beta, slow directions behave like gradient descent with step α/(1−β)\alpha/(1-\beta): a constant-factor speed-up, same exponent.
  2. Momentum has no effect on quadratics.It moves the curve by a factor of about ten.
On a log-log plot, multiplying time by a constant shifts the curve sideways without changing its slope. Changing the exponent needs step sizes and momenta that change with tt.

Practice

From ν and κ to ζBuild a power law

Let λk=k−ν\lambda_k=k^{-\nu} and λkck(0)2=k−1−κ\lambda_kc_k(0)^2=k^{-1-\kappa}. Show that ∑λk≤λλkck(0)2≈λκ/ν\sum_{\lambda_k\le\lambda}\lambda_kc_k(0)^2\approx\lambda^{\kappa/\nu}, so ζ=κ/ν\zeta=\kappa/\nu.

Solution

λk≤λ\lambda_k\le\lambda iff k≥λ−1/νk\ge\lambda^{-1/\nu}. The tail ∑k≥k0k−1−κ≈k0−κ/κ\sum_{k\ge k_0}k^{-1-\kappa}\approx k_0^{-\kappa}/\kappa, and k0−κ=λκ/νk_0^{-\kappa}=\lambda^{\kappa/\nu}. This is how the figure builds its problem: for given ν\nu and ζ\zeta it sets κ=ζν\kappa=\zeta\nu.

Momentum per directionComplex eigenvalues

For one eigen-direction, heavy ball is ct+1=(1+β−αλ)ct−βct−1c_{t+1}=(1+\beta-\alpha\lambda)c_t-\beta c_{t-1}. Write it as (ct+1ct)=M(ctct−1)\begin{pmatrix}c_{t+1}\\c_t\end{pmatrix}=M\begin{pmatrix}c_t\\c_{t-1}\end{pmatrix}, and find when MM's eigenvalues are complex. What is their modulus then?

Solution

M=(1+β−αλ−β10)M=\begin{pmatrix}1+\beta-\alpha\lambda&-\beta\\1&0\end{pmatrix} with characteristic polynomial μ2−(1+β−αλ)μ+β\mu^2-(1+\beta-\alpha\lambda)\mu+\beta. The roots are complex when (1+β−αλ)2<4β(1+\beta-\alpha\lambda)^2<4\beta, and then both have modulus β\sqrt\beta (their product is β\beta). In that regime the coordinate spirals in at rate β\sqrt\beta per step, whatever λ\lambda is: this is how momentum speeds up the flat directions.