How AI works
What is gradient descent, explained simply?
Picture looking for a valley floor in thick fog: feel which way the ground tilts, step downhill, repeat. Here's that idea as arithmetic you can check by hand, including the ways it goes wrong.
Gradient descent is a method for finding a low point of a function by taking repeated steps downhill. At each step you measure the slope where you're standing, then move in the opposite direction, and a small enough move lowers the function's value. The size of the move is the slope times a number you pick, called the learning rate. Machine learning uses it to train many models: the function is the loss, which scores the model's mistakes, and the steps adjust the model's parameters.
Gradient descent as walking downhill in fog
You're on a hillside in fog so thick you can't see your boots, and you want to reach the valley floor. You can't look for it. But you can feel which way the ground tilts right where you're standing. So you take a step downhill, stop, feel the tilt again, and take another. You keep going until the ground feels flat.
That's gradient descent. Stanford's CS231n course notes use nearly the same picture: think of yourself as hiking on a hilly terrain with a blindfold on, and trying to reach the bottom. Each part of the walk has a name in math and a job in machine learning:
| On the hillside | In math | When training a model |
|---|---|---|
| Where you're standing | The input, w | The model's parameters, the adjustable numbers inside it |
| Your altitude | The function's value at w | The loss, a score for how wrong the model is |
| The tilt under your feet | The gradient, or slope | How the loss changes as you nudge each parameter |
| How boldly you step | The learning rate | A setting you choose before training |
| The valley floor | A minimum | Parameters that give a low loss |
Why not look at a map of the whole hillside? With one adjustable number you could. Try ten values, keep the best. With two numbers, ten values each makes 100 combinations. With twenty numbers it's 1020, and a model can have thousands or billions. The slope is something you can measure from where you're standing, and it tells you which way to go. In a 2017 survey of these methods, Sebastian Ruder calls gradient descent by far the most common way to optimize neural networks.
How gradient descent works, one step at a time in numbers
Put the fog on paper. Say your position along a trail is w, and your altitude there is (w − 5)². The low point is at w = 5, where the altitude is 0. You know that because you can see the formula. The walker can't see it, and can only ask about the spot they're on. They start at w = 0, at an altitude of 25.
Feel the tilt. Shuffle a hair to the right, to w = 0.01. The altitude there is (−4.99)² = 24.9001. It fell 0.0999 over a distance of 0.01, so the slope is about −0.0999 ÷ 0.01 = −9.99. Calculus gives a formula for the exact slope of this trail, 2 × (w − 5), which says −10 at w = 0. When a function has several inputs, the list of its slopes, one per input, is called its gradient.
Step the other way. A negative slope means altitude falls as w goes up, so go up. A positive slope means altitude rises as w goes up, so go down. Either way you move against the sign of the slope, and that's where the minus sign in the update rule comes from:
new w = old w − learning rate × slope
Take a learning rate of 0.1. The first step goes from 0 to 0 − 0.1 × (−10) = 1, where the altitude is 16. The slope there is 2 × (1 − 5) = −8, so the next step lands on 1 + 0.8 = 1.8. Keep going:
| Step | w | Altitude | Slope | Next move |
|---|---|---|---|---|
| 0 | 0 | 25 | −10 | +1 |
| 1 | 1 | 16 | −8 | +0.8 |
| 2 | 1.8 | 10.24 | −6.4 | +0.64 |
| 3 | 2.44 | 6.55 | −5.12 | +0.512 |
| 4 | 2.952 | 4.19 | −4.096 | +0.410 |
| 5 | 3.362 | 2.68 | −3.277 | +0.328 |
| 10 | 4.463 | 0.29 | −1.074 | +0.107 |
| 21 | 4.954 | 0.002 | −0.092 | +0.009 |
The learning rate stayed at 0.1 the whole way, yet the moves got smaller, because the slope gets gentler near the bottom. Each step closes 20% of whatever gap is left, so the walker gets very close to 5 without ever landing on it exactly. Google's Machine Learning Crash Course says the same about training: a model almost never finds the exact weight and bias values that minimize loss, but instead finds values very close to them. In practice you stop after a set number of steps, or when the loss has all but stopped falling, which is called convergence.
Why a small step against the slope goes down
Zoom in on a smooth hillside and it looks like a straight ramp. A ramp with slope −10 says a move of +1 should drop you by 10. The real drop was 9, from 25 to 16, because the ground curves and flattens out along the way. A smaller move of +0.1 should drop you by 1, and the real drop is 0.99. The smaller the step, the more the ramp tells the truth.
That argument is older than computers. The method is usually credited to the French mathematician Augustin-Louis Cauchy, who published it in October 1847 because he wanted to compute the orbits of heavenly bodies by solving equations with six unknowns. Claude Lemaréchal's short history translates his claim: step against the slopes, and the function's value will become smaller than u if θ is small enough, where u is the value you started from and θ is what we now call the learning rate. Cauchy promised a follow-up paper with the details. According to Lemaréchal, it doesn't seem to exist.
What happens when the learning rate is too small or too big
CS231n points out a catch with the gradient: it gives a direction, but it does not tell us how far along this direction we should step. That's the learning rate's job, and on the trail with altitude (w − 5)² you can work out exactly what each choice does. Every step multiplies your gap to the bottom by the same number:
gap multiplier = 1 − learning rate × curvature
Curvature is how fast the slope changes as you move. On this trail the slope is 2 × (w − 5), so it rises by 2 for every unit of w, and the curvature is 2. Here are six learning rates, all starting from w = 0:
| Learning rate | Gap multiplier | w after steps 1, 2, 3, 4 | Altitude after 10 steps | What happens |
|---|---|---|---|---|
| 0.01 | 0.98 | 0.1, 0.198, 0.294, 0.388 | 16.69 | Crawls. 228 steps to close 99% of the gap |
| 0.1 | 0.8 | 1, 1.8, 2.44, 2.952 | 0.29 | Settles. 21 steps to close 99% |
| 0.5 | 0 | 5, 5, 5, 5 | 0 | Lands on the bottom in one step |
| 0.9 | −0.8 | 9, 1.8, 7.56, 2.952 | 0.29 | Zigzags across the bottom, still settles in 21 |
| 1.0 | −1 | 10, 0, 10, 0 | 25 | Bounces between the same two spots forever |
| 1.1 | −1.2 | 11, −2.2, 13.64, −5.368 | 958.4 | Climbs out of the valley, faster each time |
The multiplier explains every row. Between 0 and 1, the gap shrinks smoothly. Between −1 and 0, you overshoot and land on the far side, but closer than before, so overshooting on its own isn't failure. Below −1, each step lands farther away than the last one. For any bowl whose curvature stays the same as you move (a quadratic, like this one), that gives a clean cutoff. In Gabriel Goh's derivation on Distill, with α for the learning rate and λ for each of the bowl's curvatures, a step size works only if 0 < αλ < 2 for every one of them. The curvature here is 2, so the learning rate has to stay below 1.
With most real models you can't just read the curvature off a formula, and it changes as you move. Cornell's machine learning notes say plainly that setting the learning rate is a dark art, and that a rate that's too large can make the algorithm easily diverge out of control. So people try several rates and watch the loss. If it falls steadily but at a snail's pace, the rate is probably too small. If it jumps around without settling, the rate may be too big (small batches of data, covered below, add wobble of their own). If it keeps shooting up, the rate is past the limit.
Gradient descent with many parameters, and why narrow valleys are slow
A model with many parameters has one slope per parameter, and gradient descent updates them all at once with the same rule. Getting those slopes by nudging, the way the walker did at w = 0, gets expensive fast. CS231n works through a model with 30,730 parameters, where one update took 30,731 evaluations of the loss function. So real systems compute the slopes with calculus. In a neural network that job is called backpropagation, and our explainer on what a neural network is runs it by hand.
More parameters bring a new problem, and two are enough to show it. Say the altitude is a² + 10b². The bottom is at a = 0, b = 0. The slopes are 2a and 20b, so the valley curves ten times more sharply along b than along a. It's long and narrow.
One learning rate has to serve both directions. Along b the curvature is 20, so the rate must stay under 2 ÷ 20 = 0.1, or the walk never settles. Use 0.09 and start at a = 10, b = 2. The gradient is (20, 40), so the step is (1.8, 3.6) and you land on (8.2, −1.6). Each further step multiplies a by 0.82 and b by −0.8:
The first step is a surprise if you expected downhill to point at the bottom. The bottom is 10 to the left and 2 down. The step goes 1.8 left and 3.6 down, about 52° off course. The downhill direction is the steepest way down from this spot, and in a narrow valley that's mostly across the valley, with only a little progress along it.
The most sharply curved direction caps the learning rate, and the flattest direction then crawls. The table uses the best possible fixed learning rate for each shape of bowl, which Distill derives as 2 divided by the sum of the smallest and largest curvature. The ratio in the first column is called the condition number.
| Largest ÷ smallest curvature | Size of the gap multiplier | Steps to close 99% of the gap |
|---|---|---|
| 1 (a round bowl) | 0 | 1 |
| 10 | 0.818 | 23 |
| 100 | 0.980 | 231 |
| 1,000 | 0.998 | 2,303 |
Three common fixes for a narrow valley
- Rescale the inputs. Feeding a model square footage in the thousands next to a bedroom count of 3 gives you a narrow valley. Scikit-learn's guide warns that stochastic gradient descent is sensitive to feature scaling, so it is highly recommended to scale your data. In the two-parameter example, measuring b in units that bring its curvature down to 2 makes the bowl round, and a learning rate of 0.5 reaches the bottom in one step.
- Add momentum. Each step also keeps a fraction of the previous step, usually 0.9 or a similar value. The back-and-forth moves mostly cancel and the steady ones add up.
- Give every parameter its own step size. Adam, a popular variant, computes adaptive learning rates for each parameter. Its authors describe it as based on adaptive estimates of lower-order moments, which means running averages of each parameter's recent slopes and squared slopes.
Does gradient descent always find the lowest point?
No. Gradient descent finds a low spot, and whether it's the lowest depends on the shape of the function and where you start. If the function is convex, meaning bowl-shaped with no separate dips, there's no wrong valley to end up in. That's the case for linear regression with the usual squared-error loss. Google's course on it says the loss functions for linear models always produce a convex surface. Neural networks lose that guarantee. CS231n says their objective functions will become non-convex, with complex, bumpy terrain in place of bowls.
Here's a bumpy trail with two valleys: altitude = w⁴ − 4w² + w + 6. Its slope is 4w³ − 8w + 1. Run gradient descent twice with the same learning rate, 0.05, starting at 0.1 and at 0.2. Those starting points are almost touching, but there's a hilltop between them, near w = 0.126. After 20 steps:
| Start | Slope at the start | Ends at | Altitude there |
|---|---|---|---|
| w = 0.1 | +0.204, so it moves left | w = −1.473 | 0.56 |
| w = 0.2 | −0.568, so it moves right | w = 1.347 | 3.38 |
Both stopping points are local minima: lower than anything right around them. Only the left one is the global minimum, the lowest point anywhere. From the floor of the shallow valley, both directions are uphill, including the one that leads to the deep valley, so plain gradient descent stays put.
Flat spots and saddle points
The dots in the figure bunch up near the hilltop, where the slope is close to zero. Flat ground slows the walk wherever it is, on a valley floor or not. Start exactly on the hilltop and you'd never move at all.
With two or more parameters, a flat spot can also look like a mountain pass: up in some directions, down in others. That's a saddle point. A 2014 paper by Yann Dauphin and colleagues argued that for high-dimensional problems the deeper difficulty comes from the proliferation of saddle points, not local minima, because saddles are surrounded by plateaus that slow learning and can look like a local minimum. There's a reassuring result too. For smooth functions where every flat point that isn't a local minimum has at least one downward-curving direction, a 2016 paper showed that gradient descent from a random start with a small enough fixed step converges to a local minimizer or negative infinity almost surely. (Negative infinity covers functions with no bottom at all. The full theorems come with technical conditions, such as the walk settling somewhere in the first place.) "Almost surely" isn't the same as "soon", though. Crossing a plateau can take a long time.
So with the neural networks people train in practice, reaching the lowest point usually isn't guaranteed. Training depends on finding "good" minimizers of highly non-convex loss functions, as a 2017 paper on loss surfaces puts it. The same paper notes that some network designs produce loss functions that are easier to train on, so the shape of the hillside is partly a choice.
Batch, stochastic and mini-batch gradient descent compared
A model's loss is usually an average over its training examples, so an exact slope means going through all of them. The three named versions of gradient descent differ in how many examples they use to measure the slope before each step.
A small case shows the trade. Say w is a single guess, the data is the four numbers 2, 4, 6 and 8, and the loss is the average of (w − number)². That average works out to (w − 5)² + 5, the same valley as the first trail, just 5 units higher, so every slope is the same as before. At w = 0 the four examples on their own give slopes of −4, −8, −12 and −16, which average to −10. Use a random pair, say 2 and 6, and you get −8: a bit off, but the right direction, for half the work.
Now stand at the bottom, w = 5. The four slopes are 6, 2, −2 and −6. They average to exactly 0, but each one alone still pushes you away. That's why stepping on one random example at a time, with a fixed learning rate, doesn't settle down here: it keeps jittering around the bottom. The usual cure is to lower the learning rate as training goes on. Ruder's 2017 survey says that when you slowly decrease the learning rate, the one-example version ends up converging the way the full-data version does.
| Version | Examples per step | Steps per pass over 1,000 examples | The trade |
|---|---|---|---|
| Batch (full-batch) | All of them | 1 | Exact slope, expensive steps |
| Stochastic (SGD) | 1 | 1,000 | Cheap steps, jumpy path |
| Mini-batch | A small group, such as 100 | 10 | Fairly steady, still cheap |
Mini-batch is typically the algorithm of choice when training a neural network, according to Ruder, who puts common sizes between 50 and 256, varying by application, and adds a naming trap: people often say SGD when they mean mini-batches. For how batches fit into a full training run, see our guide to how an AI model is trained.
Where beginners go wrong about gradient descent
- "The gradient points at the answer." It points along the steepest slope from where you stand, uphill, which is why the update rule subtracts it. Even reversed, it only points straight at the bottom in special cases such as a round bowl. In the narrow valley above, it was 52° off.
- "Gradient descent and backpropagation are the same thing." Backpropagation computes the slopes. Gradient descent uses them to take a step. You can run gradient descent with no backpropagation at all, as the walker on the (w − 5)² trail did.
- "A zero slope means you've arrived." A hilltop, a saddle point and a plateau can all have a slope at or near zero. Zero slope means gradient descent has nothing left to follow, and that's all it means.
- "The steps won't shrink unless you shrink the learning rate." With exact slopes on a smooth valley, a fixed learning rate that isn't too big gives shrinking steps by itself. Lowering the rate matters more with mini-batches, where each slope is a noisy estimate.
- "If the loss goes up on one step, something is broken." With mini-batches, a wobble is normal, because each step is measured on different examples. With the full dataset, a rise means that step was too big for the ground it was on. A loss that climbs step after step is the sign to lower the learning rate.
- "The lowest training loss makes the best model." Gradient descent lowers the loss you give it. A model can drive that close to zero by memorizing its examples and still fail on new ones, which is called overfitting.
Common questions
What's the difference between gradient descent and backpropagation?
Backpropagation works out the slope of the loss for every parameter in a neural network. Gradient descent then uses those slopes to move each parameter a little downhill. Training a network alternates the two, over and over.
What's a good learning rate for gradient descent?
There's no universal value, because the right one depends on how sharply the function curves. On a simple bowl, the learning rate times the curvature has to stay between 0 and 2. For real models, people try several values of very different sizes and keep one where the loss falls quickly without jumping around.
Why is it called gradient descent?
The gradient is the list of slopes of a function, one per input, and descent means going down. The method goes down by stepping against the gradient. It's also called steepest descent, although some authors save that name for the version that picks the best step length every time.
Do I need calculus to understand gradient descent?
Not for the idea. You can estimate a slope by nudging an input and seeing how much the output changes, then step the other way. Calculus gives exact slopes much faster, and machine learning libraries do that part for you.
Can gradient descent get stuck?
Yes. It can settle in a local minimum that isn't the lowest point, or slow to a crawl on flat ground near a saddle point. Starting from different places, adding momentum or using noisy mini-batches can all help, but none of them guarantees the lowest point.
Learn it properly
This article walked downhill by hand. Math for Machine Learning covers the same ground in short lessons with exercises: what derivatives and gradients measure, then a lesson on optimization where you take steps yourself, tune the step size, and see what momentum and saddle points do.
Sources
- CS231n: Optimization, Stochastic Gradient Descent · Stanford University
- An overview of gradient descent optimization algorithms · Sebastian Ruder, arXiv, 2017
- Linear regression: Gradient descent · Google Machine Learning Crash Course
- Cauchy and the Gradient Method · Claude Lemaréchal, Documenta Mathematica, 2012
- Why Momentum Really Works · Gabriel Goh, Distill, 2017
- CS4780 Lecture 7: Gradient Descent (and Beyond) · Cornell University
- Stochastic Gradient Descent: Tips on practical use · scikit-learn documentation
- Adam: A Method for Stochastic Optimization · Kingma and Ba, arXiv, 2014
- Identifying and attacking the saddle point problem in high-dimensional non-convex optimization · Dauphin et al., arXiv, 2014
- Gradient Descent Converges to Minimizers · Lee, Simchowitz, Jordan and Recht, arXiv, 2016
- Visualizing the Loss Landscape of Neural Nets · Li et al., arXiv, 2017
Read next
How is an AI model actually trained, step by step?
An AI model is trained by making guesses, scoring the errors with a loss function and nudging its numbers downhill with gradient descent, step by step.
What is a transformer in AI, and what does attention do?
A transformer is the neural network design behind ChatGPT. Attention lets every word pull in meaning from the words that matter to it. Here it is, worked by hand.
Why does AI make things up (hallucinate)?
AI chatbots make things up because they predict likely text instead of looking facts up, and training rewards guessing. Here's how it happens and how to check.