Gradients and gradient descent

Intermediate

Introduction

So far a function had one input. Real problems have many: a house price depends on size, age and location, and a neural network's loss depends on millions of weights. The tools stay the same, applied one variable at a time. The result is the gradient, the compass of optimization: it points where a function rises fastest, so walking the other way lowers the function. This lesson builds the gradient and uses it for gradient descent in two variables.

How it works

For f(x, y) = x² + 3y² there are two slopes at any point. The partial derivative ∂f/∂x is the slope when only x moves and y is held fixed, so y² acts like a constant: ∂f/∂x = 2x. In the same way ∂f/∂y = 6y. The gradient collects them in a vector: ∇f = (2x, 6y). At the point (1, 2) it equals (2, 12), which says f rises 12 per unit step in y and only 2 per unit step in x.

Important fact: the gradient points in the direction of steepest increase, and its length is that steepest slope. Where the gradient is the zero vector, the surface is flat in every direction: a peak, a valley or a saddle.

To check a formula, estimate each partial derivative with a central difference: change only x by ±h for the first, only y for the second. The example prints exact and numeric gradients at (1, 2); they match.

Gradient descent in two variables repeats the update (x, y) ← (x, y) − rate × ∇f. The example starts at (4, 3) with rate 0.1. Each step the x part is multiplied by 1 − 0.1 × 2 = 0.8 and the y part by 1 − 0.1 × 6 = 0.4, so both shrink toward the minimum at (0, 0), y faster than x.

The learning rate must suit the steepest direction. Here a rate above 1/3 would make the y part grow (1 − 6 × rate would be less than −1), even though x would still be fine. Real loss functions are often stretched like this, with one steep and one gentle direction, which is why training can zigzag and why rates are tuned. We usually stop when the length of the gradient, √(gx² + gy²), is below a small tolerance.

Example

def f(x, y):
    return x * x + 3 * y * y

def grad_exact(x, y):
    return [2 * x, 6 * y]

def grad_numeric(x, y, h=1e-5):
    gx = (f(x + h, y) - f(x - h, y)) / (2 * h)
    gy = (f(x, y + h) - f(x, y - h)) / (2 * h)
    return [round(gx, 4), round(gy, 4)]

print("exact gradient at (1, 2):", grad_exact(1, 2))
print("numeric gradient at (1, 2):", grad_numeric(1, 2))

x, y = 4.0, 3.0
print("start", (x, y), "f =", round(f(x, y), 4))
for step in range(1, 6):
    gx, gy = grad_exact(x, y)
    x, y = x - 0.1 * gx, y - 0.1 * gy
    print("step", step, "point", (round(x, 4), round(y, 4)), "f =", round(f(x, y), 4))
Open in compiler

Line by line

  1. f is the surface. grad_exact returns (2x, 6y) from the rules of the last lesson.
  2. grad_numeric changes x alone, then y alone, with the central difference.
  3. The loop moves the point 10% of the gradient against itself, five times, and prints the new point and value of f.
  4. f drops from 43 to a small number, because the point approaches the minimum at (0, 0).

Expected result

exact gradient at (1, 2): [2, 12]
numeric gradient at (1, 2): [2.0, 12.0]
start (4.0, 3.0) f = 43.0
step 1 point (3.2, 1.2) f = 14.56
step 2 point (2.56, 0.48) f = 7.2448
step 3 point (2.048, 0.192) f = 4.3049
step 4 point (1.6384, 0.0768) f = 2.702
step 5 point (1.3107, 0.0307) f = 1.7208

In the real world

Training a machine-learning model means computing the gradient of the loss with respect to every weight and stepping against it, millions of times. Image editors, recommendation systems and language models all train this way. Engineers also use gradients to tune physical designs, and weather models use them to fit observations.

Common mistakes

  • Adding the gradient instead of subtracting it. That walks uphill and the loss grows.
  • One rate for very different directions. A rate that suits the gentle direction can blow up the steep one.
  • Treating the other variable as changing when taking a partial derivative. Hold it fixed.
  • Stopping when the loss stops falling a little. Check the gradient length instead.

Best practices

  • Verify a hand-derived gradient against central differences at a random point before running descent.
  • Print the loss during descent; if it rises, lower the learning rate.
  • Stop when the gradient length is below a tolerance, with a cap on the number of steps.
  • Scale variables to similar sizes so one rate suits all of them.

Summary

A partial derivative differentiates with respect to one variable while the others stay fixed. The gradient collects all partial derivatives into a vector that points toward steepest increase. Gradient descent subtracts a multiple of the gradient from the point, repeatedly. A learning rate that is too large for the steepest direction makes the method diverge.

Quick check

1. For f(x, y) = x² + 3y², what is ∂f/∂y?
2. The gradient of a function at a point points…
3. To lower f, gradient descent updates the point as…
4. The gradient is the zero vector at a point. What does that mean?
5. Why does a too-large learning rate hurt in the steepest direction?

Key takeaways

  • A partial derivative treats all other variables as constants.
  • The gradient points uphill, so we subtract it to go downhill.
  • A central-difference check works one variable at a time.
  • The learning rate must suit the steepest direction of the function.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.