Partial derivatives and the gradient
Be able to calculate partial derivatives and interpret the gradient as the steepest direction.
Practise in Mattegrafen ↗ · Matematik 5Prerequisites
Intuition
A function of several variables, f(x, y), is a surface. The slope depends on which way you walk.
A partial derivative ∂f/∂x: the slope if you change only x and hold y fixed. You differentiate as usual and treat y as a constant.
f(x, y) = x² + 3xy + y²
- ∂f/∂x = 2x + 3y (y constant)
- ∂f/∂y = 3x + 2y (x constant)
The gradient ∇f = (∂f/∂x, ∂f/∂y) is a vector pointing in the direction where the function grows fastest. Its length is how steep that is.
Which is why gradient descent goes minus the gradient: the steepest way down.
Formal
. At the point for : .
The directional derivative in a unit direction is — largest when points the same way as (the dot product is maximised), zero perpendicular to the gradient (you are then walking along a level curve).
At a minimum (every partial derivative is zero) — necessary but not sufficient: it could also be a maximum or a saddle point.
For a model with millions of parameters the gradient is a vector with millions of components — one per parameter. Backpropagation is the method of computing all of them in one pass, instead of one at a time.
Code
import numpy as np
def f(x, y):
return x**2 + 3*x*y + y**2
def grad(x, y):
return np.array([2*x + 3*y, 3*x + 2*y])
print(grad(1, 2)) # [8 7]
# a numerical check (always worth doing)
eps = 1e-6
num = np.array([(f(1+eps, 2) - f(1-eps, 2)) / (2*eps),
(f(1, 2+eps) - f(1, 2-eps)) / (2*eps)])
print(np.round(num, 4)) # [8. 7.]
The numerical gradient check is the standard trick when you have implemented backprop yourself: if the analytic and numerical gradients agree, the implementation is probably right.
Mastery means
- Calculates the partial derivatives of a function of two variables
- Interprets the gradient as the direction of steepest increase
Sign in to do the exercises and build your mastery up.
Sources
- Wikipedia — Gradient (CC BY-SA 4.0) — CC BY-SA 4.0
- Dive into Deep Learning (CC BY-SA 4.0) — CC BY-SA 4.0