In P0.2 you tuned two numbers, and , until a line fitted three points. You did not look for the answer by thinking. You searched: try a pair of numbers, score it with one number (the loss), try a better pair.
That search has a name, optimization, and it is not only machine learning. A delivery company chooses routes that minimize the total distance. A chef chooses the amounts of three ingredients that maximize the taste score. A model chooses its parameters that minimize its loss. The questions are the same each time. What are we allowed to change? What number do we score? Does a best choice even exist, and how do we find it?
This lesson answers those questions with one picture: a landscape you can turn around in your hands.
Three ingredients
An optimization problem has three parts.
- The parameters: the numbers we are free to choose. In P0.2 they are and . We write all of them together as (the Greek letter theta). A neural network can have millions or billions of them.
- The objective: one number that scores a choice of parameters. In machine learning it is the loss, also called the cost. These words are used loosely in the field, and some books use “cost” for the average over all the data and “loss” for one example. This course writes for one example and for the average over the training data. The objective can also be a loss plus a penalty on large weights (P3.A6), and then people call the whole thing the objective.
- What is fixed: everything we are not allowed to change while we search.
The third part is where beginners get confused, so here it is for the P0.2 setup, on the three points , , :
- Parameters (the numbers the search chooses): and . They change during the search.
- Data (the training examples): the three points. Fixed.
- Form of the model (the shape of the formula): , a line. Fixed.
- Hyperparameters (settings we choose around the search): and steps. Fixed by us.
The loss is a function of the parameters. The data are constants inside it. Change the data and you get a different landscape; change the parameters and you move around on one landscape. Hyperparameters are not part of the loss formula, but they control how the search runs. Choosing them well is a second, outer optimization problem (see “Optimization in the rest of the course” below).
The minimum and the argmin
Write the problem as
Read it as “find the smallest value of over all choices of ”. That smallest value is the minimum. The choice of parameters where it happens is the argmin, the notation from P1.A4:
They are different kinds of thing. For the P0.2 loss the minimum is the number , and the argmin is the pair . Training wants the argmin, because the argmin is the model. The minimum only tells you how good that model is on the training data.
Maximizing is minimizing the negative
Some problems ask for the largest value (a taste score, a likelihood). We do not need a second theory, because maximizing and minimizing have the same answer:
Flipping the sign turns every hill into a valley. The largest value of is minus the smallest value of . Example: a coin shows heads, heads, tails. The probability of that sequence, if the chance of heads is , is (P1.D10 calls it the likelihood). It is largest at , where it equals . Minimizing over between and gives the same . Taking a logarithm, which keeps the order of the values, turns the probability into a negative log-likelihood, , whose smallest value is at the same . That is the sense in which “maximize the likelihood” and “minimize the negative log-likelihood” are one problem (P1.D10).
A landscape you can turn
Plot the loss over all the parameters and you get a loss landscape: the parameters are the position on the ground, and the loss is the height. A good choice of parameters is low ground. With two parameters the landscape is a surface in 3-D, so you can see all of it. With the P0.2 loss it is
Each bracket is the squared error on one of the three points (P0.2). Here are a few heights, computed from the formula:
The point is the start of the P0.2 worked example, and there is the loss you computed by hand. The lowest point, with , is the best line.
Things to try:
- Start with the P0.2 loss. Turn the surface. It is a long, narrow valley with one lowest point. Press Go to a lowest point and read the height: . (P1.C8 measured how curved the valley is: in the sharpest direction and along the valley floor, so the floor is nearly flat.)
- Switch to the contour map. The thin lines connect points of equal height (P1.C5). Where they are close together the ground is steep; they shrink to a point around the lowest spot. Drag the point to another place and watch the height change.
- Choose Stretched bowl. This is the bowl of P1.F3, ten times steeper in one direction. The lowest point is .
- Choose Two valleys. The valleys have different depths: the right one is a local minimum and the left one the global minimum (more below). Press Go to the local min and read the status.
- Choose Saddle and Two multiplied weights, and read the status at every flat point you find.
The same landscape, one parameter at a time
You cannot always draw a surface, but you can always look along a line through it. Fix and let only move. The surface turns into a curve, a slice:
With a bit of algebra this slice is : a one-parameter bowl, the same kind of curve as in P1.F3. The slice along is . Both slices have their lowest point at the same place, because the lowest point of the surface lies on both lines. A slice is a cut through the landscape, and slices are the only way to look at landscapes with more than two parameters.
Kinds of low points
Not every flat or low spot is “the minimum”. Four words cover the cases.
- A global minimum is a point whose loss is less than or equal to the loss at every other point.
- A local minimum is a point whose loss is less than or equal to the loss at every point close enough to it. Zoomed in, it looks like a global minimum; zoomed out, a lower point may exist elsewhere. A global minimum is also a local one.
- A maximum is the same idea turned upside down: a hilltop.
- A flat point (also called a critical point or stationary point) is a point where the gradient is zero (P1.C5): to first order the ground is level in every direction. A minimum of a smooth loss (away from the edge of the region we search) is a flat point, and so is a maximum. But a flat point does not have to be either. At a saddle the ground goes up in some directions and down in others, like a mountain pass or a horse saddle.
Which of the three a flat point is depends on how the ground curves, and that is measured by the Hessian (P1.C8): curving up in every direction gives a minimum, curving down in every direction a maximum, a mixture a saddle, and if some direction is exactly flat the Hessian cannot decide (P1.C8). The Saddle landscape in the widget, , is flat at , yet that point is neither a minimum nor a maximum.
The Two valleys landscape shows why this matters. It is a made-up function, . Its left valley floor is at with . Its right valley floor is at with . Both are local minima, because every point close to either one is higher. Only the left one is the global minimum. Between them, at , is a pass where the gradient is also zero: it is a minimum along but a maximum along , so it is a saddle. A search that stops at the first flat point it meets may stop in the right valley. P1.F2 studies this in detail; for now, remember that every global minimum is a local minimum, but a local minimum need not be global.
Go deeper The exact definition of a local minimum
A point is a local minimum of if there is some distance such that for every with . The distance may be tiny. It is a global minimum if the inequality holds for every , with no distance limit.
It is a strict local minimum if “less than or equal to” can be replaced by “less than” for all close by. Without strictness, a flat floor makes every point of the floor a local minimum at once. That is what happens on the valley floor in the example further down.
Does a lowest point exist? Is it only one?
So far every landscape had a lowest point. Two things can go wrong.
It may not exist. The function on all real numbers is positive and gets as close to as you like (, ), but it never reaches . There is no smallest value. What it does have is a greatest lower bound, , called the infimum. A real example: logistic regression (P3.A7) on data that one straight line separates perfectly. For a single example with label and input , the loss is . It is at , at and at , and it keeps falling as grows, but never reaches . The optimizer can only follow the loss toward and stop by some other rule (see below). The Saddle landscape is another case: it keeps falling past the edge of the box in the widget, so it has no lowest point either.
It may not be unique. Take the tiny model with two parameters multiplied together, and one example , . The loss is , and it is exactly whenever : for , , and alike. Those points form two curves in the widget (the Two multiplied weights landscape), a valley floor where every point is equally low. There is one minimum value, , but infinitely many argmin points. The same thing happens in real networks. Swap two hidden neurons (with all their incoming and outgoing weights) and the network computes exactly the same function, so a good set of weights typically comes with copies. That is why the argmin is better thought of as a set of lowest points, written with a set-valued meaning (P1.A4 noted that ties are possible).
The same landscape has a flat point at where . The gradient is zero there, but nearby the loss goes down along one direction (toward the valley) and up along another, so it is a saddle, not a minimum.
Go deeper Two hidden units, swapped: a numerical check
Take a small network with two hidden units, , with . At it predicts , , . Now swap the two units: . The predictions are identical, because addition does not care about the order of its terms. So the two parameter settings have the same loss on any data, and whenever one is a minimum so is the other. A layer with hidden units can be ordered in ways; for five units that is 120.
Real models: too many parameters to draw
Two parameters give a surface you can hold. A real model has millions or billions of parameters, so its landscape lives in a space with that many directions. Nobody can draw it. What researchers show instead are slices: pick a point (often a trained set of weights) and two directions in parameter space, and plot the loss over the plane they span. A well-known 2018 study of this kind (Li and co-authors, “Visualizing the Loss Landscape of Neural Nets”) introduced a way of scaling the directions (called filter normalization) so that slices of different networks can be compared. Such pictures are real information about that plane, and they can mislead about the rest of the space. A smooth bowl in one plane says nothing certain about the other directions. This lesson shows no picture of a real network’s landscape, only the made-up and small ones above, and says so.
Go deeper Why a slice of a big landscape can mislead
A slice along two directions and from a point is the function of two numbers. It is exact on that plane. But a plane is a tiny part of a space with millions of directions. A point that looks like a minimum in the plane can still have a downhill direction outside it, and a mountain in the plane can be a pass in the full space. Slices are good for comparing landscapes under the same recipe, and weak for proving that a point is a minimum. The cut you saw above, , is the simplest case: one direction.
How do we search?
A landscape with a million parameters cannot be scanned, so how do we find low ground? There are three basic strategies.
1. Grid search: try everything on a grid. Choose values for each of the parameters and evaluate the loss at every combination. For P0.2 with values of from to and 41 values of from to , that is evaluations, and the best one is with loss (the code below runs it). With three parameters it is . With ten it is , far too many to compute. With one million parameters the count is a number with more than 1.6 million digits. The cost grows exponentially in the number of parameters . It is the same count you met for integrals on a grid (P1.C9). The fix there was to sample random points instead (Monte Carlo, P1.D9). Grid search is only reasonable for very few parameters.
2. Random search: try random points. Draw points at random and keep the best. It does not need a grid, and the cost does not explode in the same way, but in a high-dimensional space a random point is typically far from low ground. It works well when only a few of the numbers really matter. That is why it is a common way to search hyperparameters (P4.23), where there are few of them and no gradient is available.
3. Follow the slope. Stand at a point, find which direction goes downhill, take a step, repeat. This is local search, and with the gradient as the slope it is gradient descent (P1.F3). Each step uses information about the ground right here, so it does not waste evaluations on faraway regions. Computing the gradient for all parameters costs a small multiple of one loss evaluation, not evaluations, when backpropagation (P4.8) does it.
Run the comparison yourself. The test loss below is the friendly bowl , with its lowest value at . Random search gets 1000 random points in the cube . Gradient descent takes 50 steps with from a random start.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The output (medians over 20 runs): at , random search reaches and gradient descent . At the numbers are against . At random search has only moved from to , while gradient descent is at . This bowl is the easiest possible landscape, so read the table as the effect of the dimension, not as a promise that gradient descent always works that well. On a landscape with many valleys it finds a nearby valley (P1.F3), not necessarily the best one.
When do we stop?
An optimizer needs a rule for when to stop. Three common ones, often used together:
- Small gradient. Stop when is below a small threshold, because the ground is nearly flat. This is a reason to expect a flat point, but flat does not mean minimum, as the saddle showed.
- No more improvement. Stop when the loss has not fallen by a useful amount over some number of steps.
- A budget. Stop after a fixed number of steps or minutes. For large networks this is the usual rule.
A low training loss is not the final goal. The optimizer’s job is to make the loss small on the training data. What we care about is the loss on new data. A model with many parameters can reach a training loss near zero by memorizing its examples, and then do badly on new ones (P0.2 showed this with the wiggly curve). So there are two separate errors. The optimization error is how far the training loss is from its lowest possible value. The generalization error is the loss on new data, and the generalization gap is how much worse the model does on new data than on training data. Solving the optimization problem perfectly does not solve the second one. That is why we hold out validation and test data (P3.A4) and why the bias–variance view exists (P3.A5).
A related fact: the number we optimize is not always the number we report. Accuracy is a step function of the parameters, flat nearly everywhere, so it gives no slope to follow. Classifiers are therefore trained on a smooth stand-in, such as cross-entropy (P4.6), and judged on accuracy afterwards.
Optimization in the rest of the course
- Training = minimizing a loss over the weights. Linear regression and neural networks follow the P0.2 recipe: pick a loss, then search the weights (P3.A2, P4.6, P2.7). Some classic methods, such as decision trees, learn in other ways.
- Maximum likelihood and MAP. Maximum likelihood (P1.D10) chooses the parameters that maximize the probability of the data; with the sign flip above it is minimizing the negative log-likelihood. MAP (P1.D11) adds the negative log prior to this loss as a penalty, and a Gaussian prior on the weights adds an L2 penalty (P3.A6).
- Hyperparameter search is an outer problem: the objective is the validation loss, the parameters are things like , and each evaluation means a whole training run. It has no cheap gradient, which is why grid, random and Bayesian search appear there (P4.23).
- Constraints. Sometimes the parameters may not be chosen freely: probabilities must be non-negative and add to , a weight vector may be required to have a fixed length. That is constrained optimization, with its own tools (P1.F7).
Intuition
You stand on hilly ground in fog. The parameters are your position, the loss is your height, and your goal is the lowest ground. You cannot see the map. You can feel the slope under your feet, and you can check your height at any place you go. Grid search is walking to every point of a checkerboard. Random search is teleporting to random places. Following the slope is walking downhill.
Where the picture breaks: a real model’s ground has millions of directions, not two, and the “height” of every place costs a computation, so a long walk is expensive. The ground can also have flat floors with no unique lowest point, and some landscapes keep falling forever.
Math
An unconstrained optimization problem is . With data for and a model , the objective is the average loss
and the data are constants. For a smooth , a local minimum has (and a Hessian with no negative eigenvalue). The reverse does not hold: a flat point can be a saddle (P1.C8). Equivalences: , and for , because the logarithm is increasing.
A grid with values for each of parameters has points.
Code
The P0.2 loss as a function of the parameters, a grid search, the argmin against the min, a one-parameter slice, and the cost of grids in more dimensions.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Expected output: the three losses are , and . The grid minimum is at . The slice prints , , , , , . The grid costs are , , and .
Go deeper The loss you optimize and the metric you report
The thing we want, such as the share of correct answers (accuracy), often cannot be optimized directly. Accuracy changes in jumps as the parameters move, and it is flat between the jumps, so its gradient is zero almost everywhere and tells the optimizer nothing. The usual fix is a surrogate loss: a smooth function that is small when the model does well, for example cross-entropy for classification (P4.6). We optimize the surrogate and report the metric. The two usually move together, but a lower surrogate loss does not promise a higher accuracy.
Go deeper When no minimum exists: the infimum
A set of numbers may have no smallest member but still have a greatest lower bound, the infimum: the largest number that is still below or equal to all of them. The values of are all positive, and no positive number is a lower bound larger than , so the infimum is , but no produces . We write , and say the infimum is not attained. A minimum is an infimum that is attained.
Optimization problems that have an infimum but no minimum are common in the “perfect fit” case (the separable logistic loss) and make an optimizer keep pushing a weight larger and larger. Practical remedies are adding a penalty on the size of the weights (P3.A6) and stopping by one of the rules above.
Misconceptions
Check yourself
Check your understanding
You minimize the mean squared error of the line on a fixed set of examples. What does the optimization change?
The loss is a function of the parameters. The data, the form of the model and the number of examples are all fixed while we search; only and are chosen.
The P0.2 loss has its smallest value, , at . Which of these is the ?
The argmin is where the smallest value happens, a choice of parameters. The number is the minimum, the value itself. The point has a much larger loss, and is only one of the two coordinates.
A coin shows heads, heads, tails. The likelihood of that result is , largest at . For between and , which minimization gives the same answer?
Maximizing a function is the same as minimizing its negative. Minimizing itself would pick or , where it is zero. Minimizing picks , and minimizing the distance to picks , not .
A search stops at a point where every nearby point has a higher loss. What can you say for sure?
Being lowest among the nearby points is exactly the definition of a local minimum. Another valley can be lower. For a smooth loss the gradient at a local minimum is zero, not non-zero, and the lowest value of a loss does not have to be zero (it is for P0.2).
A grid search tries values for each of parameters. How many loss evaluations does it need?
A grid has one point for every combination of values, so . Adding the numbers ( or ) would count only the points along the axes. The count swaps the base and the exponent.
After training, the loss on the training set is nearly , but the loss on held-out data is large. Which statement fits best?
The optimization error (how far the training loss is from its lowest value) is small here. A large loss on new data is a generalization problem, such as overfitting. An optimizer only sees the training loss. A small training loss shows that the optimizer made progress; the trouble is on new data.
Exercises
- Evaluate the P0.2 loss at .
Show answer
the errors are , and , so , higher than the minimum . - Fix and use the slice . What is at , and for which is the slice lowest?
Show answer
at it is . It is lowest at , where it is . - Turn the maximization of into a minimization, and solve it.
Show answer
minimize . Its argmin is and its minimum value is . So has its maximum at , with value . - Does on have a minimum? A maximum?
Show answer
no minimum: it gets as close to as you like as grows, but never reaches it (infimum , not attained). It has no maximum either, because it grows without limit as approaches . - A grid search uses values for each of parameters. How many evaluations? If each takes millisecond, how long is that?
Show answer
evaluations. At ms each that is seconds, about minutes. - For , is a minimum? Is it the only one?
Show answer
yes: and a squared number cannot be below , so it is a global minimum. It is not the only one: and also give , as does any point with . - For , the gradient is . What kind of point is ?
Show answer
the gradient is zero there, so it is a flat point. Along the axis and along the axis , so it is neither a minimum nor a maximum: it is a saddle. - For the coin with heads, heads, tails, compute the negative log-likelihood at and at . Which is smaller?
Show answer
at the likelihood is , so the value is . At the likelihood is , so the value is . The value at is smaller, which is the maximum likelihood choice. - Training the line on three points with learning rate for steps: name the parameters, the data and the hyperparameters.
Show answer
parameters: and . Data: the three points. Hyperparameters: the learning rate and the number of steps . The form of the model, a line, is also fixed.
Next: the Two valleys landscape asks when a search ends in the right valley and when in the left. P1.F2 looks at which landscapes have only one valley (convex ones) and which have many. Then P1.F3 shows the step-by-step method that walks downhill on all of them.