Derivatives and Gradients

Updated · 6 min read
hardPython 3.13aimathcalculusgradientsnumpy

A derivative measures how fast something changes when its input changes a little. A partial derivative does the same for one input while the others stay fixed. A gradient is the list of partial derivatives for all of a model's parameters, and it points in the direction that increases the loss most. Training moves the parameters the opposite way, which is called gradient descent.

This lesson completes the chapter's checkpoint: compute a gradient by hand and with NumPy for a two-parameter model, and check they match.

From Loss to Gradient

Compute the slope, step downhill, repeat
IdeaDescription
DerivativeIt is used to measure how much an output changes per tiny change in an input
Partial derivativeIt is used for the change with respect to one parameter, others fixed
Chain ruleIt is used to find derivatives of functions inside functions: multiply the derivatives along the chain
GradientIt is used to collect all partial derivatives; it points uphill on the loss
Learning rateIt is used to set how big each step downhill is

The Chain Rule, by Hand

The loss is the average of (w × size + b − price)². The outer function is "square" (derivative: 2 × inside) and the inner function is "w × size + b − price" (derivative with respect to w: size; with respect to b: 1). Multiplying along the chain:

  • ∂loss/∂w = mean(2 × error × size)
  • ∂loss/∂b = mean(2 × error)

Example: Check, Then Descend

Python
import numpy as np
 
size = np.array([1.5, 2.0, 2.5])
price = np.array([300, 380, 470])
 
def loss(w, b):
    return np.mean((w * size + b - price) ** 2)
 
w, b = 150.0, 70.0
 
# By hand, with the chain rule: d/dw mean((w*x + b - y)^2) = mean(2 * error * x)
error = w * size + b - price
by_hand = (np.mean(2 * error * size), np.mean(2 * error))
 
# Numerically: nudge each parameter a tiny bit and watch the loss
h = 1e-6
numeric = ((loss(w + h, b) - loss(w - h, b)) / (2 * h),
           (loss(w, b + h) - loss(w, b - h)) / (2 * h))
 
print("By hand:  ", np.round(by_hand, 4))
print("Numerical:", np.round(numeric, 4))
print("Match:", np.allclose(by_hand, numeric))
 
# Gradient descent: step against the gradient a few times
for step in range(1, 4):
    error = w * size + b - price
    w -= 0.05 * np.mean(2 * error * size)
    b -= 0.05 * np.mean(2 * error)
    print(f"step {step}: w {w:.2f}, b {b:.2f}, loss {loss(w, b):.2f}")
Output
By hand:   [-60.     -26.6667]
Numerical: [-60.     -26.6667]
Match: True
step 1: w 153.00, b 71.33, loss 89.72
step 2: w 154.48, b 71.93, loss 51.60
step 3: w 155.23, b 72.18, loss 42.41

Explanation: The hand-derived formulas give −60 for w and −26.67 for b. The numerical check nudges each parameter up and down by 0.000001 and measures how the loss changes; the results are the same, so the formulas are right. Gradient descent then subtracts 0.05 × gradient from each parameter: because both gradients are negative, w and b grow, and the loss falls from 250 to 42.41 in three steps.

Learning Rate

Learning rateWhat happens
Too smallEach step barely helps; training takes very long
About rightThe loss falls steadily, as in the example
Too largeSteps overshoot the lowest point; the loss can grow instead of shrink

Common Mistakes

Adding the gradient instead of subtracting it. That climbs uphill and makes the loss worse.

A learning rate that's too large. If the loss jumps up, make the steps smaller.

Forgetting the chain rule's inner derivative. The × size term in ∂loss/∂w comes from the inner function.

Interview Corner

What is a gradient, and how is it used in training?

The vector of partial derivatives of the loss with respect to each parameter. It points toward increasing loss, so gradient descent updates parameters in the opposite direction, scaled by a learning rate.

How do you check that a gradient is correct?

Compare it with a numerical estimate: nudge each parameter by a tiny amount, measure the change in the loss, and confirm the two agree.

Practice

Exercise: the learning rate. Run gradient descent for 3 steps with learning rates 0.01 and 0.5. What happens to the loss each time? Explain the 0.5 result using the table above.

Check your understanding:

  1. What does the gradient point toward?
  2. Why does ∂loss/∂w contain × size?
  3. What did the numerical check confirm?

Quick check: derivatives and gradients

4 questions
1What was the gradient for w at w = 150, b = 70?
2Which way does gradient descent move parameters?
3What happens with a learning rate that's too large?
4What does the chain rule do?

Key Takeaways

Quick reference

NeedFormula or code
∂loss/∂wnp.mean(2 * error * size)
∂loss/∂bnp.mean(2 * error)
Numerical check(loss(w + h) - loss(w - h)) / (2 * h)
One stepw -= learning_rate * grad_w

Was this tutorial helpful?

Lesson 119 of 186