TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Gradient Descent and the Learning Rate

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 (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:

wt+1=wt−η ∇L(wt)\mathbf{w}_{t+1} = \mathbf{w}_t - \eta \, \nabla L(\mathbf{w}_t)

The gradient ∇L\nabla L 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 η\eta. The derivation (a first-order Taylor expansion of LL) 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 L(w)=12w⊤HwL(\mathbf{w}) = \frac{1}{2} \mathbf{w}^\top H \mathbf{w} with a symmetric positive definite matrix HH. Its gradient is HwH \mathbf{w}, so one step is

wt+1=(I−ηH) wt.\mathbf{w}_{t+1} = (I - \eta H)\, \mathbf{w}_t .

Along an eigenvector of HH with eigenvalue λ\lambda, the coordinate is multiplied by 1−ηλ1 - \eta \lambda at every step. It shrinks only when ∣1−ηλ∣<1\lvert 1 - \eta\lambda \rvert < 1, that is when 0<η<2/λ0 < \eta < 2/\lambda. The tightest condition comes from the largest eigenvalue, the direction of steepest curvature:

η<2λmax⁡.\eta < \frac{2}{\lambda_{\max}} .

Three regimes follow:

Learning rate Factor 1−ηλmax⁡1 - \eta\lambda_{\max} What you see
η<1/λmax⁡\eta < 1/\lambda_{\max} between 0 and 1 smooth, monotone descent
1/λmax⁡<η<2/λmax⁡1/\lambda_{\max} < \eta < 2/\lambda_{\max} between −1-1 and 0 zig-zag across the valley, still converges
η>2/λmax⁡\eta > 2/\lambda_{\max} below −1-1 each zig-zag is bigger than the last: divergence

Meanwhile the flattest direction, eigenvalue λmin⁡\lambda_{\min}, shrinks by only 1−ηλmin⁡1 - \eta\lambda_{\min} per step. With η\eta capped near 2/λmax⁡2/\lambda_{\max}, that factor is about 1−2λmin⁡/λmax⁡1 - 2\lambda_{\min}/\lambda_{\max}, so the condition number λmax⁡/λmin⁡\lambda_{\max}/\lambda_{\min} 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 HH), so the same picture applies locally (Curvature and the Hessian).

See it

The lab runs 60 steps of plain gradient descent on the valley 12(u2+10v2)\frac{1}{2}(u^2 + 10v^2) turned by 25 degrees. Its eigenvalues are 1 and 10, so the limit is 2/10=0.22/10 = 0.2. Start with η=0.08\eta = 0.08 (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.

−2−1012−202Loss contours: narrow valleyxy10−610−410−211001040204060stepLoss f(x, y), log scalepath / lossstartminimumGD stable for η < 0.2

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, H=diag⁡(1,10)H = \operatorname{diag}(1, 10), from the start (−2,1.5)(-2, 1.5), 50 steps for four learning rates:

python · try it yourself
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 1−ηλ1 - \eta\lambda:

  • η=0.01\eta = 0.01: the steep coordinate shrinks by 0.90.9 per step and is almost gone, but the flat one shrinks by only 0.990.99, and 1.51.5 is still −1.21-1.21 after 50 steps. Too slow.
  • η=0.1\eta = 0.1: the steep factor is exactly 1−0.1⋅10=01 - 0.1 \cdot 10 = 0, so that coordinate is solved in one step; the flat one shrinks by 0.90.9. Best of the four.
  • η=0.19\eta = 0.19: the flat direction is solved, but the steep factor is −0.9-0.9: it flips sign every step and decays slowly, so the loss is worse than at 0.1 even though the learning rate is larger.
  • η=0.21\eta = 0.21: the factor is −1.1-1.1, and 1.5⋅1.150≈1761.5 \cdot 1.1^{50} \approx 176. Diverged.

A bigger learning rate is not "faster" once you pass 1/λmax⁡1/\lambda_{\max}.

A real loss: linear regression on the diabetes data

For the half mean squared error L(w)=12n∥Xw−y∥2L(\mathbf{w}) = \frac{1}{2n}\lVert X\mathbf{w} - \mathbf{y} \rVert^2 the Hessian is the constant matrix X⊤X/nX^\top X / n, so the limit can be computed before training:

python · try it yourself
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 2/4.024=0.4972/4.024 = 0.497, 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 λmax⁡\lambda_{\max}. Practical recipes:

  1. Start from the default of the optimizer (Adam: 10−310^{-3}; SGD with momentum: about 0.010.01 to 0.10.1 for normalised networks).
  2. Sweep on a log scale: 10−4,3⋅10−4,10−3,…10^{-4}, 3 \cdot 10^{-4}, 10^{-3}, \dots, 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.
  3. LR range test: raise η\eta exponentially during one short run and plot loss against η\eta; pick a value before the curve turns up.
  4. Change it during training with a schedule: warm-up at the start, decay at the end.

Pitfalls

  • Loss is nan after 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 λmax⁡\lambda_{\max} huge and forces a tiny η\eta for every other weight.

Practice

  1. A quadratic loss has Hessian eigenvalues 0.5, 4 and 40. What is the largest stable learning rate for gradient descent, and which η\eta removes the steepest direction in a single step?
Answer

Stability needs η<2/40=0.05\eta < 2/40 = 0.05. The steepest direction is removed in one step when 1−40η=01 - 40\eta = 0, so η=1/40=0.025\eta = 1/40 = 0.025. At that rate the flattest direction shrinks by only 1−0.025⋅0.5=0.98751 - 0.025 \cdot 0.5 = 0.9875 per step.

  1. In the NumPy example, why does η=0.19\eta = 0.19 end with a larger loss than η=0.1\eta = 0.1?
Answer

On the steep axis the factor is 1−0.19⋅10=−0.91 - 0.19 \cdot 10 = -0.9, so that coordinate only shrinks by 10 % per step (while flipping sign); after 50 steps it is 1.5⋅0.950≈0.00771.5 \cdot 0.9^{50} \approx 0.0077. At η=0.1\eta = 0.1 the factor is 0, so the steep coordinate is exactly zero after one step.

  1. You double every feature value of a standardised data set (multiply XX by 2). How does the stable learning rate for linear regression change?
Answer

The Hessian X⊤X/nX^\top X / n is multiplied by 4, so λmax⁡\lambda_{\max} is 4 times larger and the limit 2/λmax⁡2/\lambda_{\max} is 4 times smaller.

Test yourself

Plain gradient descent on a quadratic with largest Hessian eigenvalue λmax⁡=10\lambda_{\max} = 10 is stable for which learning rates?

  1. η<0.1\eta < 0.1
  2. η<0.2\eta < 0.2
  3. η<1\eta < 1
  4. η<10\eta < 10

The path zig-zags across a narrow valley but still reaches the minimum. Where is the learning rate?

  1. Below 1/λmax⁡1/\lambda_{\max}
  2. Between 1/λmax⁡1/\lambda_{\max} and 2/λmax⁡2/\lambda_{\max}
  3. Above 2/λmax⁡2/\lambda_{\max}
  4. Exactly at 2/λmax⁡2/\lambda_{\max}

On the diabetes regression the stable limit was about 0.497, yet even η=0.4\eta = 0.4 had not reached the optimum after 200 steps. Why?

  1. The loss is not convex
  2. The smallest eigenvalue is tiny (a flat direction), so progress along it is slow
  3. The learning rate was too large
  4. The bias column was missing

The training loss becomes nan after 20 steps. What is the first thing to try?

  1. Train for more epochs
  2. Lower the learning rate, for example by a factor of 10
  3. Remove the validation set
  4. Increase the learning rate