Gradient Descent and the Learning Rate
The training loop ends every step with an update: move the parameters a little against the gradient. How far is "a little" is the learning rate, written (eta). It is the single most important hyperparameter of almost every model trained by gradient methods. Too small and training crawls; too large and the loss bounces around or explodes to infinity. This lesson shows exactly where the boundary between "slow", "good" and "diverges" lies, on a surface you can see and on a real regression problem.
The update rule
Gradient descent repeats one line:
The gradient points uphill, in the direction where the loss grows fastest, so subtracting it walks downhill. Its length shrinks near a minimum, so steps get shorter on their own even with a fixed . The derivation (a first-order Taylor expansion of ) is in Gradient Descent and, with convergence proofs, in Optimization: Gradient Descent.
Why there is a speed limit
Take the simplest curved loss, a quadratic bowl with a symmetric positive definite matrix . Its gradient is , so one step is
Along an eigenvector of with eigenvalue , the coordinate is multiplied by at every step. It shrinks only when , that is when . The tightest condition comes from the largest eigenvalue, the direction of steepest curvature:
Three regimes follow:
| Learning rate | Factor | What you see |
|---|---|---|
| between 0 and 1 | smooth, monotone descent | |
| between and 0 | zig-zag across the valley, still converges | |
| below | each zig-zag is bigger than the last: divergence |
Meanwhile the flattest direction, eigenvalue , shrinks by only per step. With capped near , that factor is about , so the condition number decides how many steps plain gradient descent needs. Real neural-network losses are not quadratic, but near a minimum they look like one (the Hessian takes the place of ), so the same picture applies locally (Curvature and the Hessian).
See it
The lab runs 60 steps of plain gradient descent on the valley turned by 25 degrees. Its eigenvalues are 1 and 10, so the limit is . Start with (smooth), then try 0.15 (the path zig-zags across the narrow direction), then 0.21: the path is thrown out of the plot and the lab reports that the loss is diverging.
Switch the surface to the Rosenbrock "banana": the curvature changes along the way, so a learning rate that is fine on the flat part of the valley can be too large in the steep part (near the minimum the limit is about 0.197).
The same experiment in NumPy
The axis-aligned version of the valley, , from the start , 50 steps for four learning rates:
import numpy as np
H = np.diag([1.0, 10.0]) # f(w) = 1/2 w^T H w, eigenvalues 1 and 10
def f(w):
return 0.5 * w @ H @ w
def grad(w):
return H @ w
for lr in [0.01, 0.1, 0.19, 0.21]:
w = np.array([-2.0, 1.5])
for step in range(50):
w = w - lr * grad(w)
print(f"lr {lr:4.2f} after 50 steps w = ({w[0]:9.4f}, {w[1]:11.4f}) loss {f(w):.3e}")lr 0.01 after 50 steps w = ( -1.2100, 0.0077) loss 7.324e-01
lr 0.10 after 50 steps w = ( -0.0103, 0.0000) loss 5.312e-05
lr 0.19 after 50 steps w = ( -0.0001, 0.0077) loss 2.988e-04
lr 0.21 after 50 steps w = ( -0.0000, 176.0863) loss 1.550e+05
Read it with the factors :
- : the steep coordinate shrinks by per step and is almost gone, but the flat one shrinks by only , and is still after 50 steps. Too slow.
- : the steep factor is exactly , so that coordinate is solved in one step; the flat one shrinks by . Best of the four.
- : the flat direction is solved, but the steep factor is : it flips sign every step and decays slowly, so the loss is worse than at 0.1 even though the learning rate is larger.
- : the factor is , and . Diverged.
A bigger learning rate is not "faster" once you pass .
A real loss: linear regression on the diabetes data
For the half mean squared error the Hessian is the constant matrix , so the limit can be computed before training:
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True) # 442 patients, 10 features
X = StandardScaler().fit_transform(X)
X = np.column_stack([X, np.ones(len(y))]) # bias column
n = len(y)
def loss(w):
r = X @ w - y
return r @ r / (2 * n) # half mean squared error
hess = X.T @ X / n # constant Hessian of this loss
lam = np.linalg.eigvalsh(hess)
print(f"largest eigenvalue {lam[-1]:.3f}, smallest {lam[0]:.4f} -> stable for lr < {2 / lam[-1]:.3f}")
best = loss(np.linalg.lstsq(X, y, rcond=None)[0])
print(f"best possible loss (least squares) {best:.2f}")
for lr in [0.01, 0.1, 0.4, 0.5]:
w = np.zeros(X.shape[1])
for step in range(200):
w -= lr * X.T @ (X @ w - y) / n
print(f"lr {lr:4.2f} loss after 200 steps {loss(w):12.2f}")largest eigenvalue 4.024, smallest 0.0086 -> stable for lr < 0.497
best possible loss (least squares) 1429.85
lr 0.01 loss after 200 steps 1661.94
lr 0.10 loss after 200 steps 1437.81
lr 0.40 loss after 200 steps 1432.69
lr 0.50 loss after 200 steps 114010.13
The prediction holds: 0.4 is the best of the four and 0.5, just above , blows up. Even at 0.4 the loss is not yet at the least-squares optimum 1429.85, because the smallest eigenvalue is 0.0086: correlated features make a long flat valley, with condition number about 470. (The whole data set is used here because the point is optimisation, not generalisation; scaling on all of it is a shortcut you would not take when evaluating a model.)
Standardising the features is what made the largest eigenvalue small and predictable. On raw features with very different scales the condition number explodes and no single learning rate suits every direction. That is one reason to scale inputs (Which Models Need Scaling) and the motivation for momentum and per-parameter rates such as Adam.
Finding a learning rate in practice
For a neural network nobody computes . Practical recipes:
- Start from the default of the optimizer (Adam: ; SGD with momentum: about to for normalised networks).
- Sweep on a log scale: , a few hundred steps each, and keep the largest value whose loss goes down smoothly. The best rate is usually a factor of 3 to 10 below the one that diverges.
- LR range test: raise exponentially during one short run and plot loss against ; pick a value before the curve turns up.
- Change it during training with a schedule: warm-up at the start, decay at the end.
Pitfalls
- Loss is
nanafter a few steps. Almost always a learning rate above the stability limit (or an overflow); lower it by 10 before suspecting anything else. - Changing the batch size without the learning rate. The gradient's scale and noise change with the batch (Batch Size, Iterations and Epochs).
- Judging by the first few steps. A rate just below the limit can look worse early (zig-zag) and better later, or the reverse; compare at the step budget you will actually use.
- Unscaled features. One feature in the thousands makes huge and forces a tiny for every other weight.
Practice
- A quadratic loss has Hessian eigenvalues 0.5, 4 and 40. What is the largest stable learning rate for gradient descent, and which removes the steepest direction in a single step?
Answer
Stability needs . The steepest direction is removed in one step when , so . At that rate the flattest direction shrinks by only per step.
- In the NumPy example, why does end with a larger loss than ?
Answer
On the steep axis the factor is , so that coordinate only shrinks by 10 % per step (while flipping sign); after 50 steps it is . At the factor is 0, so the steep coordinate is exactly zero after one step.
- You double every feature value of a standardised data set (multiply by 2). How does the stable learning rate for linear regression change?
Answer
The Hessian is multiplied by 4, so is 4 times larger and the limit is 4 times smaller.
Test yourself
Plain gradient descent on a quadratic with largest Hessian eigenvalue is stable for which learning rates?
The path zig-zags across a narrow valley but still reaches the minimum. Where is the learning rate?
- Below
- Between and
- Above
- Exactly at
On the diabetes regression the stable limit was about 0.497, yet even had not reached the optimum after 200 steps. Why?
- The loss is not convex
- The smallest eigenvalue is tiny (a flat direction), so progress along it is slow
- The learning rate was too large
- The bias column was missing
The training loss becomes nan after 20 steps. What is the first thing to try?
- Train for more epochs
- Lower the learning rate, for example by a factor of 10
- Remove the validation set
- Increase the learning rate