Zero Labs
Industry News / AI

Gradient Descent Explained

Source · Towards AI By Sanika Tare

From the publisher’s feed, collected in the ZeroLabs newsroom.

Backprop told the network what went wrong. Now it has to actually fix it.At the end of the last article, backpropagation had done its job. Every weight in the network had a gradient attached, a little note saying which way it should move. But a note doesn’t change anything. The weights are still exactly where they were.Something has to take those gradients and act on them. That something is gradient descent, and the intuition is simple: find the direction that reduces the error, and take a step that way.Quick recapInput → Forward pass → Prediction → Loss → Backpropagation → GradientsGradient descent uses those gradients to update the weights.What is gradient descent?It’s an iterative optimization algorithm for finding the minimum of a function. In a neural network, that function is the loss, and the goal is to make it as small as possible.The name is literal. Gradient: we use the slope of the loss. Descent: we go down it. Each update moves the weights toward a point with lower loss.The mountain analogyImagine standing on a foggy mountainside. You can’t see the valley, but you can feel which way the ground tilts. Here’s how the picture maps to the math:• The landscape is the loss, drawn over all possible weight values.• Height is the amount of error.• The valley floor is low loss, where we want to be.• The gradient points in the direction of steepest increase, straight uphill.So we walk the opposite way.Reading a gradient: sign and size• Positive gradient: increasing the weight raises the loss, so the weight should go down.• Negative gradient: increasing the weight lowers the loss, so the weight should go up.• Large gradient: the slope is steep. The loss is very sensitive to this weight, so the update is big.• Small gradient: the slope is nearly flat. We’re either close to a minimum or this weight barely matters, so the update is small.The sign gives the direction. The magnitude gives the urgency.The formulaw_new = w_old − η × ∂L/∂w• w_old: the current weight• w_new: the updated weight• L: the loss• ∂L/∂w: the gradient of the loss with respect to that weight• η: the learning rate, which scales the stepWhy do we subtract?Because the gradient points toward increasing loss, and we want decreasing loss. If you add the gradient you climb the mountain. Subtract it and you descend. One minus sign, and that’s the whole difference between learning and making things worse.Learning rate: the dial that matters mostThe learning rate decides how much of the gradient we actually use. It’s a hyperparameter, so you choose it before training begins.A numerical exampleSuppose the current weight is 2, the gradient is 0.5 and the learning rate is 0.1.w_new = 2 − (0.1)(0.5) = 1.95The gradient was positive, so the loss was rising with the weight. The weight gets nudged down a little, and a little is the point. We moved by 0.05, a tenth of the gradient. That caution keeps us from stepping over the valley.Gradient descent step by stepInitialize weights↓Make prediction↓Calculate loss↓Calculate gradients (backprop)↓Update weights↓Calculate loss again↓RepeatFrom one weight to billionsReal networks have hundreds, thousands, millions, and sometimes billions of parameters. The idea doesn’t change. Backprop produces one gradient per parameter, and gradient descent applies the same update rule to every one of them at once.Batch, stochastic and mini-batchHow much data should we look at before each update? There are three answers.What is an epoch?• Dataset: all your training samples.• Batch: the group of samples used for one update.• Iteration: one update, meaning one batch processed.• Epoch: one full pass over the dataset.1000 training samples, batch size = 1001000 / 100 = 10 iterations10 iterations = 1 epochWhat does convergence mean?Early in training the loss drops quickly. As we approach a minimum the slope flattens, the gradients shrink, and so do the updates. Eventually the loss stops improving much and training stabilizes. That’s convergence.Local vs global minimumThe mountain analogy is tidy, but real loss landscapes are messy. They can have several valleys. The deepest is the global minimum. The shallower ones are local minima, where the slope is zero but better solutions exist elsewhere.In practice, in very high-dimensional networks, this turns out to be less scary than it looks, but it’s a good reason not to treat optimization as a solved, simple problem.Where basic gradient descent struggles• Learning can be slow.• Updates can oscillate back and forth across a narrow valley.• A poorly chosen learning rate can stall or wreck training.• Different parameters may need different update sizes.These problems motivated smarter optimizers, which we’ll meet in a later piece: Momentum → RMSProp → Adam.See it in NumPyLet’s fit a single weight. With x = 2 and target y = 10, the ideal weight is 5. We start at 0.import numpy as npx, y = 2.0, 10.0w, lr = 0.0, 0.05for i in range(21):y_hat = w * x # predictionloss = 0.5 * (y_hat — y) ** 2 # lossgrad = (y_hat — y) * x # gradientif i in (0, 1, 2, 5, 10, 20):print(f”iter {i:2d} w={w:.4f} loss={loss:.4f}”)w = w — lr * grad # updateiter 0 w=0.0000 loss=50.0000iter 1 w=1.0000 loss=32.0000iter 2 w=1.8000 loss=20.4800iter 5 w=3.3616 loss=5.3687iter 10 w=4.4631 loss=0.5765iter 20 w=4.9424 loss=0.0066The weight climbs toward 5 and the loss collapses. The early steps are big because the gradient is big, and they shrink as we get close. That’s convergence in five lines of math.Common beginner questionsWhy can’t we just pick the best weights? There are far too many combinations, and we don’t know the landscape in advance. We can only feel the local slope, so we walk.Why do we need a learning rate? The gradient only describes the slope right where we stand. A full step could carry us past the valley, so we take a fraction.What if it’s too high? We overshoot, bounce around, and the loss may even increase.What if it’s too low? Training works, but takes forever and can stall.Is gradient descent the same as backprop? No. Backprop finds gradients. Gradient descent spends them.What’s an epoch? One full pass through the training data.Why does loss usually decrease? Because every step is taken in the direction that locally reduces it.Bringing it all togetherForward propagation → Prediction → Loss→ Backpropagation → Gradients→ Gradient descent → Updated weights→ Better predictionThat loop is how a neural network learns, whether it has three weights or three billion.But there’s a catch. A network can get brilliant at its training data by the very process we just described, and then fall apart on data it has never seen.What happens when a network performs extremely well on training data but fails on new, unseen data?Gradient Descent Explained was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.