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.
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 , find a function with , then predict 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.
The theorem says a good network exists; it does not say how wide it must be, or how to find its weights. Smaller generally needs more parameters, and under smoothness assumptions on one can say how many. In the figure, a ReLU network with hidden units is the piecewise-linear interpolant at points; for twice-differentiable its error falls like .
Explore
Worked example
A network with one hidden layer of two ReLU units: , , output . Evaluate it at and .
Forward pass at .
, . .
Forward pass at .
, . .
Count the parameters, and say what the network looks like as a function.
First layer: a 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 is piecewise linear with at most four pieces, cut by the lines and . 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:
- Any continuous function, given enough layers.Composing affine maps never leaves the affine maps.
- Only affine functions .
Universal approximation guarantees that:
- Training by gradient descent will find a network within of the target.It says nothing about training.
- Some network within of the target exists, of some size.
- A network with a fixed number of units can approximate every continuous function.The size depends on and on the target.
In the figure, the steep step needs many more units than sin for the same error. Why?
- Piecewise-linear interpolation error is controlled by the target's slope and curvature, and the step is very steep in one place.
- ReLU networks cannot represent increasing functions.Each unit is increasing; sums of them certainly can be.
Practice
The hat functionThree ReLUs make a bump
Write the hat as a combination of ReLUs .
Solution
. Check: for all are 0; on it is ; on it is ; for , . 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 equally spaced pieces on , how many hidden units are needed to approximate to within ?
Solution
, , so the error is at most . Need : . Ten times more accuracy costs only about times more units, because is smooth.
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 and a first hidden layer of three nodes. Each node has its own weights and bias:
and outputs . Stacking the weights in a matrix, the whole layer is with of size : row holds node 's weights. The next layer takes as its input in exactly the same way, and so on.
Training chooses . Once it is chosen, the network is just a fixed function , and evaluating it is the forward pass you can step through below.
Explore
Worked example
The network in the figure has , , , ReLU in the hidden layers and none at the output. Evaluate it at .
First hidden layer: compute , then .
. ReLU zeroes the negatives: .
Second hidden layer.
, so .
Output.
. Set the sliders to and check.
Now remove every activation. What single affine map is the network?
with (a matrix) and . 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:
- It multiplies the previous layer's vector, which has 128 entries, so it needs 128 columns.
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?
- Not at all: it stays at 0 while its sum is negative.
- Linearly with the input.Only on the positive side of its kink.
Does the bias matter? Without biases, a ReLU network always satisfies:
- and for .
- Nothing special; biases only shift the output.Try in every layer.
Practice
Counting parametersA wider, deeper network
Count the parameters of a network (an image classifier for 28-by-28 images). Which layer has the most?
Solution
. 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 with one hidden layer of ReLU units. Each unit is off on one side of a line. At most how many regions can the lines cut the plane into, and what does the network look like on each one?
Solution
lines in general position cut the plane into 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 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.
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
Examples. integrates directly: . For , separate the variables: , so and . In general one can write , but that is circular as a recipe: the unknown is inside the integral.
Sup, not max. is the least upper bound, which always exists for a bounded set of real numbers; a maximum need not. On , has supremum 1 but no maximum, since 1 is never reached. When a maximum exists the two agree, so writing 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, . Check the shapes: is square, , , are column vectors and is a scalar, so is a column vector. Setting gives an autonomous field, one that does not depend on time.
Explore
Worked example
Why the theorem needs a compact set and a finite horizon.
Solve , . What happens?
Separate: , so and . It blows up at . On with there is no solution to approximate.
Take and . Does every solution exist on , and how large does it get?
Yes: blow-up happens at . The largest value is from . Everything stays in the compact interval , which is where the network needs to be accurate.
Why can't one network work for all and all ?
Solutions from large 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 everywhere. Restricting to a compact and finite keeps all the trajectories inside one bounded region. In the figure, drag far out or raise and watch the error grow.
Check your understanding
The flow map for a system in is a function from:
- to curves in .That is what you get when is allowed to vary.
- to : starting point to position at time .
- to .That describes one trajectory , with fixed.
Why train one network for all starting points rather than one network per trajectory?
- One network approximates the law of motion , which predicts trajectories from starting points never observed.
- It is cheaper to train.Maybe, but the real reason is what you learn.
In the figure, the trajectories of the fitted field drift away from the true ones as grows, even with a good fit. Why?
- Small errors in the velocity accumulate along the trajectory and can grow over time.
- The numerical solver loses accuracy after a while.The same solver is used for both fields.
Practice
A linear flowFlow maps compose
For with constant, find and show .
Solution
, so is multiplication by the matrix , and . Flowing for and then for is flowing for . This holds for any autonomous field; with a time-dependent the maps depend on the start time too.
Grönwall in one lineHow errors grow
Let and with , everywhere and -Lipschitz. Show .
Solution
satisfies . Grönwall's lemma gives when and in general. So a velocity error of costs at most on , which is why controlling the sup error of the field controls the sup error of the flow on a finite horizon.
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 in a unit direction is the directional derivative , where is the angle between them. It is most negative when , that is, when points opposite to . So
The gradient says which way to go, not how far: the learning rate is a choice. In machine learning is the average loss over the data, and computing its gradient through the network's layers is backpropagation.
Explore
Worked example
, so . Start at .
With : the per-step factors in each coordinate, and .
and . So : the steep coordinate is solved in one step, and after that. Reaching takes steps.
With ?
Factors and . The second coordinate flips sign and grows by 1.5 each step: divergence, since .
What is the best fixed , and how fast is it?
Balance the two factors: , so and both have size . About 35 steps for three digits. Momentum improves this to roughly per step.
Check your understanding
Why step against the gradient rather than along it?
- is smallest at : the loss falls fastest opposite to the gradient.
- Along the gradient the step would be too long.Length is set by ; direction is the issue.
On an ill-conditioned quadratic () plain gradient descent is slow because:
- must be below for the steep direction, which makes progress in the flat direction tiny.
- The gradient points away from the minimum.It points downhill, just not at the minimum: it zigzags across the valley.
Doubling the batch size changes the mini-batch gradient's standard deviation by a factor of:
- That is the variance, not the standard deviation.
- : the noise comes from the data, not the batch.Averaging more independent samples reduces it.
Practice
The gradient of a quadraticThree lines
For with symmetric, show , find the minimizer, and rewrite gradient descent as .
Solution
by symmetry, and . The minimizer solves . Then ; subtract .
Momentum on a lineThe characteristic equation
Apply heavy ball to . Show that satisfies , and find when it converges for , .
Solution
Substitute . The roots of have product ; the iteration converges iff both have modulus below 1, which (Jury's test) means : . Momentum enlarges the stable range from to .
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 , , and a per-example loss ,
One full gradient step costs per-example gradients.
The consequence: with a fixed step size , SGD does not converge to the minimizer. It reaches the neighbourhood quickly and then jitters around it, at a scale set by and the noise. Decreasing over time (a schedule) or increasing shrinks the jitter.
Explore
Worked example
Fit to four points , with . Take .
Compute each and the full gradient.
Residuals ; gradients . Full gradient .
List the mini-batch gradients for all six batches of size 2.
, , , , , . They range from to .
Average them.
, 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:
- Noise in the labels .The data are fixed once collected; full-batch descent on them is deterministic.
- Which examples happened to be drawn into the batch.
- Rounding errors.Those are tiny and not the point.
You quadruple the batch size. Per step, the gradient's standard deviation:
- halves, and each step costs four times as much.
- quarters, at four times the cost.That's the variance.
In the figure, with and a large step, the SGD path ends in a cloud around the minimizer rather than at it. To land closer you could:
- Decrease the step size over time, or use bigger batches.
- Run more steps with the same settings.The cloud has a fixed size for fixed α and |B|: more steps just wander inside it.
Practice
UnbiasednessProve it
Let be indices drawn independently and uniformly from . Show and (coordinatewise), where is computed per coordinate.
Solution
Each draw has and variance . is the average of independent copies: same mean, variance divided by .
EpochsCounting passes
With examples and , 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.
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: .
The idea
The model. . Check the objects: are column vectors, is a symmetric matrix, so and are numbers and is a number. The gradient with respect to (the variable we choose; and are given) is , so the minimizer has .
Where comes from. For a linear model with squared loss, averaged over data, the Hessian is . Note the order: is a number (inner product), is a matrix (outer product). is the covariance of the inputs, so its eigenvalues measure how much the data vary in each direction.
Momentum and acceleration. With constant and , heavy ball behaves like gradient descent with step on the slow directions: a constant-factor gain, the same exponent . Schedules that vary with (built from orthogonal polynomials such as Chebyshev or Jacobi polynomials) can roughly double the exponent to 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 steps of any such method the error is for a polynomial of degree with (for gradient descent, ). 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 in the complex plane enclosing all the eigenvalues,
which for diagonalizable is the scalar formula applied to each eigenvalue. Some recent work designs optimizers by choosing the contour instead of the polynomial, and complex numbers are natural there: the per-direction iteration of a momentum method is a matrix whose eigenvalues are complex when it oscillates.Explore
Worked example
, , , step .
Per-step factors and .
and : , then . The first direction is solved immediately.
The loss, and how many steps to reduce it by a factor of 1000.
. Need : . All of that time is spent on the flat direction.
Could a larger step help?
Only up to , where the steep factor is . At the flat factor is , about 175 steps, but the steep direction now oscillates with factor . The best fixed step balances the two at , giving for . 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 , the object is:
- The number .That is .
- A matrix of rank one.
“Spectral decomposition of the error vector ” means:
- Computing the eigenvalues of .A vector has no eigenvalues; the spectrum is 's.
- Writing as a combination of the eigenvectors of .
In the figure, raising the momentum from 0 to 0.9 shifts the heavy-ball curve but leaves its slope at about . Why?
- With constant , slow directions behave like gradient descent with step : a constant-factor speed-up, same exponent.
- Momentum has no effect on quadratics.It moves the curve by a factor of about ten.
Practice
From ν and κ to ζBuild a power law
Let and . Show that , so .
Solution
iff . The tail , and . This is how the figure builds its problem: for given and it sets .
Momentum per directionComplex eigenvalues
For one eigen-direction, heavy ball is . Write it as , and find when 's eigenvalues are complex. What is their modulus then?
Solution
with characteristic polynomial . The roots are complex when , and then both have modulus (their product is ). In that regime the coordinate spirals in at rate per step, whatever is: this is how momentum speeds up the flat directions.