← All posts

Machine learning algorithms › Training and evaluation

What is gradient descent? How a model learns in small steps

What gradient descent is, how the learning rate and batch size change training, and why feature scaling matters, worked through with small numpy examples.

If you’re learning machine learning, the name gradient descent probably showed up fairly early. The optimizer line in neural network training code usually sets up some form of it, and the learning rate and number of epochs you choose before training are settings of gradient descent, too. Part of why the name comes up so often these days is that deep learning, which sits behind many of today’s AI tools, leans on it heavily. The textbook Deep Learning says that nearly all of deep learning is powered by one very important algorithm, stochastic gradient descent.

Gradient descent is an optimization method that computes the gradient of the loss and moves the parameters a little in the direction that lowers the loss, over and over. The loss is a single number for how wrong a model’s predictions are, and the parameters are the numbers the model learns, such as weights and a bias. Since it’s a way of training a model, it’s used to fit a single straight line and to train large neural networks alike.

What one step is made of

The first part is the gradient. For each parameter there’s a number that tells you how much the loss changes when you nudge that parameter up a little. If the number is positive, you lower the parameter to reduce the loss, and if it’s negative, you raise it. Taken together, these numbers make up the gradient, which points the way the loss grows fastest, so gradient descent moves the opposite way. The second part is the learning rate, which sets how far to move each time. It’s a hyperparameter, a setting a person chooses before training. The third part is the update. In words, it’s new weight = current weight - learning rate × gradient, applied to every parameter at once, and repeated until the loss stops falling or a set number of steps is done.

Fitting a straight line by hand

The code below uses numpy to make 100 noisy points around the line y = 3x + 2 and asks the model, predicted value = weight × x + bias, to find the weight and bias starting from zero. The seed is fixed, so you’ll get the same numbers on every run. The loss is the mean squared error, the average of the squared gaps, and since its gradient can be written down directly, grad_w and grad_b compute it. I ran the same 1,000 steps with three learning rates.

import numpy as np

rng = np.random.default_rng(seed=0)
x = rng.uniform(0, 10, size=100)
y = 3 * x + 2 + rng.normal(0, 1, size=100)  # y = 3x + 2 plus noise

def loss(w, b):
    return np.mean((w * x + b - y) ** 2)  # mean squared error

def gradient_descent(lr, steps=1000):
    w, b, losses = 0.0, 0.0, []
    for _ in range(steps):
        error = w * x + b - y
        grad_w = 2 * np.mean(error * x)  # gradient for w
        grad_b = 2 * np.mean(error)      # gradient for b
        w -= lr * grad_w                 # step against the gradient
        b -= lr * grad_b
        losses.append(loss(w, b))
    return w, b, losses

print(f"start: loss {loss(0, 0):.4g}")
print("lr      step 1     step 10    step 100   step 1000  w          b")
for lr in (0.0001, 0.02, 0.03):
    w, b, losses = gradient_descent(lr)
    cols = " ".join(f"{losses[s - 1]:<10.4g}" for s in (1, 10, 100, 1000))
    print(f"{lr:<7} {cols} {w:<10.4g} {b:.4g}")
start: loss 420.3
lr      step 1     step 10    step 100   step 1000  w          b
0.0001  413.7      358.2      85.45      1.448      3.193      0.5192
0.02    152.7      1.419      1.028      0.9401     2.987      1.992
0.03    823.8      3.564e+05  8.331e+31  4.062e+295 -9.976e+146 -1.402e+146

With a learning rate of 0.02, the loss fell from 420.3 to 1.419 in just 10 steps, and the weight and bias reached 2.987 and 1.992. With 0.0001, on the other hand, the steps were too small. After 1,000 steps the bias was still at 0.519, and the weight had grown to 3.193 to make up for it. With 0.03, the loss rose to 823.8 on the very first step and kept climbing to 4.062e+295. Each step jumped past the lowest point and landed farther away on the other side, which is called divergence. It’s a bit like turning the shower handle too far every time, so the water swings between too cold and too hot.

Batch, stochastic, and mini-batch gradient descent

Every step above used all 100 examples to compute the gradient. That’s called batch gradient descent, and with millions of rows, each single step would mean a full pass over the data. That’s why people often use stochastic gradient descent (SGD), which uses one randomly chosen example per step, or mini-batch gradient descent, which uses a small random group. One full pass over the training data is called an epoch, so with 100 examples in batches of 10, one epoch is 10 steps.

Method Examples per step What it’s like
Batch gradient descent All of them Steady, but costly on large data
Stochastic gradient descent (SGD) One Cheap steps, but very noisy
Mini-batch gradient descent A small group, often 32 to 256 A middle ground, common in deep learning

According to the Deep Learning book, most deep learning algorithms use this middle ground, and it’s common to call them simply stochastic methods (chapter 8). The code below trains on the same data with batches of 10 and a learning rate of 0.01, and prints the loss on all 100 examples after every step.

def minibatch_sgd(lr=0.01, batch_size=10, epochs=2):
    rng = np.random.default_rng(seed=0)
    w, b = 0.0, 0.0
    for epoch in range(1, epochs + 1):
        order = rng.permutation(len(x))  # reshuffle every epoch
        losses = []
        for start in range(0, len(x), batch_size):
            batch = order[start:start + batch_size]
            error = w * x[batch] + b - y[batch]
            w -= lr * 2 * np.mean(error * x[batch])
            b -= lr * 2 * np.mean(error)
            losses.append(loss(w, b))  # loss on all 100 examples
        print(f"epoch {epoch}: " + " ".join(f"{l:.3g}" for l in losses))

minibatch_sgd()
epoch 1: 9.46 1.55 1.58 1.69 1.61 1.5 1.5 1.55 1.5 1.49
epoch 2: 1.49 1.48 1.51 1.57 1.48 1.48 1.46 1.45 1.45 1.44

After a single epoch, the loss was already 1.49. In that same single pass, batch gradient descent took just one step and was still at 152.7 despite its larger learning rate, so moving ten times per pass clearly paid off. In return, the loss goes up and down, from 1.55 to 1.69 and from 1.48 to 1.57, because a gradient computed from 10 examples is only an estimate of the full one. This noise doesn’t fade even near the bottom. That’s why the Deep Learning book says the learning rate should be lowered gradually, and scikit-learn’s SGDRegressor shrinks the learning rate by default as the steps add up.

When features are on very different scales

Every parameter shares a single learning rate, so trouble starts when features have very different ranges. Say you’re predicting delivery time from the distance (500 to 5,000 meters) and the number of items (1 to 10). I made up the data as minutes = 0.004 × distance + 1.5 × items + 5, plus noise. The gradient for the distance weight is far larger, so a learning rate low enough to keep that weight from overshooting barely moves the other ones. That’s why you standardize, subtracting each feature’s mean and dividing by its standard deviation so every feature has a mean of 0 and a standard deviation of 1. For the raw features I picked a learning rate of 0.0000001, because 0.00000012 already diverged.

rng = np.random.default_rng(seed=1)
distance = rng.uniform(500, 5000, size=200)  # meters
items = rng.integers(1, 11, size=200).astype(float)
minutes = 0.004 * distance + 1.5 * items + 5 + rng.normal(0, 2, size=200)

def run(X, lr, steps=10000):
    X1 = np.column_stack([X, np.ones(len(X))])  # last column is for the bias
    params, losses = np.zeros(3), []
    for _ in range(steps):
        grad = 2 * X1.T @ (X1 @ params - minutes) / len(minutes)
        params -= lr * grad
        losses.append(np.mean((X1 @ params - minutes) ** 2))
    return " ".join(f"{losses[s - 1]:.4g}" for s in (10, 100, 1000, 10000))

X_raw = np.column_stack([distance, items])
X_std = (X_raw - X_raw.mean(axis=0)) / X_raw.std(axis=0)  # standardize
print("loss after 10/100/1000/10000 steps")
print("raw, lr 1e-7:         ", run(X_raw, 1e-7))
print("standardized, lr 0.1: ", run(X_std, 0.1))
loss after 10/100/1000/10000 steps
raw, lr 1e-7:          85.93 51.26 51.04 48.87
standardized, lr 0.1:  10.39 3.131 3.131 3.131

With raw features, the loss was still 48.87 after 10,000 steps. When I checked separately, the first-step gradient was about -148,000 for distance and about -283 for items, roughly 500 times apart. After standardizing, the learning rate could be a million times larger, and by step 100 the loss had reached 3.131, the lowest loss least squares finds for this data. scikit-learn’s guide also says SGD is sensitive to feature scaling and highly recommends scaling your data (tips).

How it differs from solving in one go

Linear regression can actually be solved without gradient descent. Least squares finds the weights in a single calculation, and scikit-learn’s LinearRegression does exactly that with scipy.linalg.lstsq. On the line data from earlier, it gives 2.987 and 1.993, which agree with the gradient descent answer to two decimal places.

So why use gradient descent at all? There are two reasons. The first is that many models have no such formula. With squared error, a linear regression’s loss is convex, shaped like a bowl with a single lowest point, so when gradient descent converges, it has reached that point (Google’s crash course). A neural network’s loss, however, is mostly non-convex. It can have low spots that aren’t the lowest (local minima) and places that rise in some directions and fall in others (saddle points). That’s why neural networks are usually trained with optimizers that follow the gradient again and again (chapter 6). The second reason is the size of the data. A one-shot calculation gets more expensive as the data grows, while a mini-batch step costs about the same, and scikit-learn’s guide, too, suggests SGDRegressor for regression problems with more than 10,000 samples.

From Cauchy to Adam

Optimization textbooks trace the method to a short note by Augustin-Louis Cauchy on a general method for solving systems of equations, printed in the French Academy of Sciences’ Comptes rendus for October 18, 1847 (Lemaréchal, 2012). The stochastic side leads back to Herbert Robbins and Sutton Monro’s 1951 paper A Stochastic Approximation Method. It showed how to find, step by step, the setting at which an experiment’s average response reaches a given value, even though each result varies randomly, and a review by Léon Bottou and colleagues names it as where SGD began.

Many improvements followed. Momentum keeps moving in the direction of an average of past gradients, so steps that agree add up and back-and-forth steps cancel each other out. Adam, which Diederik Kingma and Jimmy Ba posted in December 2014, estimates the average of the gradients and the average of their squares to adjust the learning rate separately for each parameter. Its name comes from adaptive moment estimation, too. Of course, you’ll rarely write these by hand. scikit-learn’s SGDRegressor and SGDClassifier train linear models with SGD, and deep learning frameworks collect these methods as optimizers, as PyTorch does in torch.optim.

When it fits and what to watch

Gradient descent fits well when there’s a lot of data and the loss changes smoothly with the parameters, so the gradient can be computed. Linear regression, logistic regression, and neural networks all qualify. For a small linear model, though, a direct solver like LinearRegression is simpler.

There are three things to watch. For the learning rate, try a few values a factor of 10 apart and watch the loss over the first steps, lowering the rate if the loss climbs and raising it if the loss barely moves. Standardize your features, but fit the scaler on the training data only. And decide when to stop. In scikit-learn 1.9.1, SGDRegressor checks the loss once per epoch and stops when the loss fails to improve by tol=0.001 for n_iter_no_change=5 epochs in a row. Even if that never happens, it stops at max_iter=1000 epochs (stopping criterion).

If you’re trying it for the first time

I’d suggest starting with the first code block and changing the learning rate to values between 0.02 and 0.03 to find where divergence begins. You can also set batch_size in the mini-batch code to 1 and to 100 to compare SGD with batch gradient descent. For real data, start by putting StandardScaler and SGDRegressor in a pipeline, as scikit-learn’s guide recommends. I ran these examples on November 2, 2026, on macOS with Python 3.13.12, NumPy 2.5.4, and scikit-learn 1.9.1.

AI tools helped with the research for this post.