Stand on a hillside. Ask “how steep is it?” and a hiker answers “which way?”. Facing east the ground may rise steeply, and facing north it may be almost flat. One hill, many slopes.
A model is a hillside too. In P0.2 the line had two numbers to tune, and the loss was 6. Raising a little made the loss fall at a rate of 10 per unit (slope ). Raising a little lowered it at the rate of . Two nudges, two different answers. This lesson gives those answers a name, the partial derivatives, and shows how to compute them for any number of inputs.
A function of several inputs
In P1.C1 the function had one input: put in , get a loss. A real loss has many inputs. The loss of the P0.2 line is a function of two, . A neural network with a million weights has a loss with about a million inputs. Everyday examples are the same: the area of a rectangle depends on its width and its height, and the price of a taxi ride depends on distance and waiting time.
With two inputs we can still draw the function. Put the inputs on the floor, as a point , and plot the output as a height above that point. The result is a surface . Our hillside is such a surface: east and north are and , and the height of the ground is .
With three or more inputs we cannot draw it, but everything below works the same way, and the picture with two inputs is the one to keep in mind.
Change one input at a time
Take the function
at the point . Its height there is . Now run two separate experiments with a small nudge of .
- Nudge , keep . Move from 2 to 2.01. The new height is , a change of , so the change per unit of nudge is .
- Nudge , keep . Move from 1 to 1.01. The new height is , a change of , so the change per unit of nudge is .
The two ratios differ: reacts more to than to here. Repeat with a nudge of and the ratios are and . As the nudge shrinks they close in on 7 and 6. These two numbers are the partial derivatives of at . Each is a limit of the ratios from P1.C1, with one input moving and the others frozen.
The slice picture
Freeze . Then is a function of alone:
On the surface, freezing means cutting with a vertical wall that stands over the line . Where the wall meets the surface you get a curve, the slice. It is the graph of , an ordinary curve, and P1.C1 and P1.C2 apply to it: , so . The slope of the slice is the number we measured by nudging.
Things to try with the slice widget:
- With the bowl at , slice along : the slope is . Switch to slice along : the slope is . Same point, two slices, two slopes. Move the slider while slicing along : the height of the slice changes, but its slope stays (this surface has for every ).
- Choose the saddle at . Along the slice rises (slope ), along it falls (slope ). Slide both inputs to : both slopes are , yet the slice along is a valley bottom and the slice along is a hilltop. A point with slope 0 in both directions is not always a minimum.
- Choose the tilted plane. Each slope is the same at every point ( along , along ): a plane tilts the same way everywhere.
- Choose the loss at its start, . Slicing along gives slope and along gives : the two numbers from P0.2. Move to : both slopes are , and the loss there is , the lowest value of this loss (P0.2 found the same point).
The definition and the notation
Take a function and a point . The partial derivative with respect to is the derivative of the slice in which is frozen at :
Only the first input moves, from to . The second stays at . In the same way
As in P1.C1, a partial derivative exists only if the limit exists. For nearly all functions in this course it does.
There are several ways to write it, and all of them mean the same thing:
- : “the partial derivative of with respect to ”. In machine learning you will often see .
- : the same, short, with the input as a subscript. (If already has subscripts in your problem, prefer the other forms.)
- : an operator that says “take the partial derivative in ”, written in front of the function.
- , or : the value at the point .
Why a curly and not ? In P1.C1, was used for a function of one input, where nothing else can vary. The curly is a warning label: this function has other inputs, and they are being held fixed. Two things follow. First, the answer usually depends on those other inputs too (see the next section: contains a ). Second, if really has only one input, and are the same number. As with in P1.C1, read as one symbol, not as the fraction “ divided by ”.
Computing partial derivatives
Here is the rule, and it is the whole trick:
Example 1. .
- With respect to , treat as a constant. The first term gives . In the is a constant multiple of , so it gives . So .
- With respect to , treat as a constant. The term has no in it, so it is a constant and its slope is 0. In the is a constant multiple of , so it gives . So .
At : and . These are the numbers the nudges were heading for. The first is also the slope of the slice .
Note two things the example shows. A partial derivative is a new function of all the inputs: changes with (at it is ). And only terms without the variable vanish: the disappears when we differentiate in , but the does not disappear when we differentiate in . It turns into .
Example 2. . This is a product, but with respect to the factor is just a constant multiplier:
At these are and .
Example 3. . With respect to the factor is constant, and with respect to the exponential rule of P1.C2 applies:
At these are and .
Three inputs. Nothing new is needed. For , freeze two inputs and differentiate in the third:
At the function is and the three partials are , and .
The surfaces of the widget. For the bowl : and . For the saddle : and . For the tilted plane : and . Compare with what the widget showed.
Check without the rules. As in P1.C1, a central difference tests a partial derivative: nudge one input up and down by a small and leave the others alone. For the three examples, with in 64-bit floats, the estimates agree with the rules to at least nine digits:
- at : the rules give and , nudging gives and .
- at : the rules give and , nudging gives and .
- at : the rules give and (rounded), nudging gives the same digits.
What a partial derivative tells you
Sensitivity. says how strongly the output reacts to a nudge of alone, in output units per input unit (as in P1.C1). Its sign says whether rises or falls as increases, and its size says how fast. Different inputs can have very different sensitivities at the same point, like the and above, or the and of the loss below.
Several nudges at once. If you nudge by and by , to first order the two effects simply add:
For at with and this predicts . The true change is . The error is small compared with the nudges, and it shrinks faster than they do. This is the several-input version of the tangent-line approximation of P1.C1, and later lessons develop it. It is also what makes gradient descent work: all weights are nudged at once, each by its own slope.
What counts as a variable depends on the question. In a loss the training data are fixed numbers, and the question is about and . Take the single prediction instead. Then answers “how does the prediction react to the weight?”, and answers “how does it react to the input?”. Same function, different question, different partial derivative. Always say with respect to what.
The P0.2 loss: two slopes at once
Now we can keep the promise of P1.C1. The model is , the three data points are , and the loss is the mean squared error
At the errors are and , as in P0.2.
To get the partial derivatives with the rules of P1.C2, expand each square and add the three. The sums are , , , , , so
(Check: at it is .) Now freeze one parameter at a time:
At :
These are the slopes of P0.2. Nudging by gave and ; a nudge of gives and ; a central difference with gives and .
Look back at P1.C1 and P1.C2: their loss was with the bias fixed at . That is the slice of this surface, , and its derivative is exactly with . So the slope of P1.C1 was a partial derivative all along.
Things to try with the nudge widget:
- Keep , and nudge up by with fixed: the loss goes from to about , and the estimate is about . Choose the nudge : the estimate is about . Now nudge : , then about .
- Choose “down (−)”. Nudging down by makes the loss rise (to about ), and the estimate is about : still negative, because a negative slope means “loss falls as the parameter rises”.
- Move to , . The exact partials are and , both positive, so the loss falls if you lower both.
- Move to , : both exact partials are and the loss is .
Reading the pair. At both slopes are negative, so the loss falls if we raise and raise . The slope for is bigger in size ( against ), so a nudge of is the more effective one right now. (This compares loss per unit of with loss per unit of . It says nothing about which parameter is better to change in the long run.)
Both at once. Write the two partials as a list:
This list is the gradient of at , written . P1.C5 shows why it points uphill, so that its opposite points downhill. For now the useful fact is that one number per parameter is all that gradient descent needs: move each parameter against its own partial derivative. With the learning rate of P0.2:
The new line is and the loss is (rounded), down from : the one step of P0.2. (The formulas also give and at , the best line of P0.2. Solving such equations for a line fit is P3.A2.)
Many weights, one partial each
A loss with weights has partial derivatives, one per weight. A network with a million weights has a million of them. Each is computed the same way: change that weight, keep the rest fixed, and see how the loss reacts. The list of all of them is the gradient, which is the whole input of gradient descent (P1.F3).
Linear functions. The building block of a neuron is the dot product (P1.B3), . Freeze all weights except . Then and are constants with slope 0, and has slope . So for every :
In list form (the gradient with respect to , P1.C5) this says .
For example, with and the output is , and the three partials are , whatever the weights are. A weight multiplies one input, so its slope is that input: a weight attached to a large input moves the output a lot, and a weight attached to an input of has no effect on it. Check by nudging: raising from to changes the output from to , a change of for a nudge of , which is a slope of . A bias adds one more term, , with .
A squared error on one example. Let and . Then
These are the formulas in the Math tab of P0.2 (there they are averaged over the examples). Getting them needs the chain rule of P1.C3, because sits inside the square, so here they are stated and checked. With , , and we get , and the formulas give for the three weights. Nudging each weight in turn gives the same numbers.
Checking a gradient by nudging, and what it costs
P1.C1 introduced the central difference as a check on a derivative. For many inputs you repeat it for each input in turn: nudge up and down while the others stay fixed, then , and so on. That is two loss evaluations per weight. (A forward difference needs one extra evaluation for the starting value, then one per weight.)
For the 3-weight example above that is 6 evaluations. For a model with weights it is . For a million weights it is two million, and each evaluation means running the model on the data. That is far too slow to do at every training step.
Backpropagation (P4.8) and automatic differentiation (P1.C10) get all partial derivatives for a cost that is a small constant multiple of the cost of one loss evaluation, however large is. So the nudging method is kept for what it is good at: checking that the fast method has no bugs, on a small model. This is gradient checking.
Go deeper Partial derivatives can exist where the surface misbehaves
A surprise from the definition. Let for , and . On the -axis () the function is everywhere, and the same on the -axis. So both slices through the origin are flat, and and : both partial derivatives exist.
But along the diagonal the function is for every , while . So the surface has a jump at the origin: a function with both partial derivatives there that is not even continuous. The two axis directions simply do not see the diagonal.
The lesson: partial derivatives look only along the axes. A standard theorem says that if the partial derivatives exist and are continuous near a point, the surface does look like a tilted plane when you zoom in, as in P1.C1. The losses in this course are smooth in that sense away from corners such as ReLU’s. The full statement is developed in later lessons.
Go deeper Second partial derivatives, and the order of differentiation
Partial derivatives are functions, so they can be differentiated again, in either input. For we found and . Differentiate in and you get . Differentiate in and you also get : the order did not matter. For both orders give , which is at .
This holds whenever the second partial derivatives are continuous near the point (Schwarz’s theorem, often called Clairaut’s), which covers the smooth losses of this course. There are rare functions where the two orders differ. The table of all second partials, the Hessian, and its meaning for curvature are the topic of P1.C8.
The partial derivative in three depths
Intuition
A function of several inputs is a landscape, and the partial derivative is the slope you feel when you walk along one axis only, with the other input frozen: east, but not north. Cut the landscape with a vertical wall and you get an ordinary curve whose slope is the answer.
For a model, answers “if I nudge only this weight, how much does the loss change per unit of nudge?”. One question per weight, and the answers together say how to nudge all the weights at once.
Math
Computation: treat the other inputs as constants and use the rules of P1.C2. Notations: , , .
First-order effect of two nudges: .
Linear function: and . Squared error (chain rule, P1.C3): .
Central difference for the -th input: , two evaluations per input.
Code
def partial(f, point, i, h=1e-5):
"""Central-difference estimate of the partial derivative of f
with respect to input number i (counting from 0) at `point`."""
up, down = list(point), list(point)
up[i] += h
down[i] -= h
return (f(*up) - f(*down)) / (2 * h)
f = lambda x, y: x**2 + 3 * x * y
partial(f, (2, 1), 0) # about 7
partial(f, (2, 1), 1) # about 6PyTorch gives every partial derivative at once with automatic differentiation (P1.C10). This runs in Colab or on your machine, not in the browser here:
import torch
x = torch.tensor(2.0, requires_grad=True)
y = torch.tensor(1.0, requires_grad=True)
f = x**2 + 3 * x * y
f.backward()
print(x.grad, y.grad) # tensor(7.) tensor(6.)Try it: one input at a time
The first cell estimates partial derivatives by nudging one input at a time, for the functions of this lesson. The second finds both slopes of the P0.2 loss and shows how the cost of nudging grows with the number of weights. Predict the output before you run.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: add at and predict both partial derivatives before you run it.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: change the code to use 1000 weights (all equal to 0.1, and ) and print the number of loss evaluations.
Common mistakes
Check your understanding
Let . What is at the point ?
Treat as a constant: . The value is , the slope in the other direction. The value forgets the factor , and adds the two partial derivatives, which are different quantities.
Which statement describes at the point of a surface ?
The partial derivative in freezes at , cuts the surface with that wall, and takes the ordinary slope of the slice. The direction of fastest climb is the gradient (P1.C5), a change of both inputs together is a different quantity, and an average height is not a slope.
For the P0.2 loss at we have and . If you raise only by and keep at 0, about how does the loss change?
The change is about , a fall. The value uses the slope for instead of , the rise has the wrong sign, and would be the fall if were nudged by as well.
Let with and , so that . What is ?
The weight multiplies , so raising it by 1 changes the output by . The value is the value of , not a slope, the value is the output itself, and is the slope for the third weight.
You check a hand-derived gradient of a loss with 1000 weights using a central difference for every weight. About how many evaluations of the loss does this take?
Each weight is nudged up and down separately while the others stay fixed, which is two evaluations per weight. Nudging all weights together would mix their effects and give only one number, not one partial derivative per weight. There is no pairing of weights in this check.
Exercises
- For , evaluate and at .
Show answer
and . - Find both partial derivatives of , and evaluate them at .
Show answer
and . At : and . - Find both partial derivatives of , and evaluate them at .
Show answer
and . At : and . - For , find all three partial derivatives at .
Show answer
, , . - What are both partial derivatives of at ? What does this say about the surface?
Show answer
and , the same at every point. The surface is a flat tilted plane, with the same tilt everywhere. - Use the formulas of this lesson to find and of the P0.2 loss at . Which way should each parameter move to lower the loss?
Show answer
and . Both are positive, so the loss falls if both and are lowered. - At , where , estimate the change in the P0.2 loss if is lowered by with fixed.
Show answer
About : the loss rises. (Exactly: , a rise of .) - For with , what are the three partial derivatives? What does the mean?
Show answer
, the entries of . The means the second weight multiplies an input equal to 0, so changing that weight does not change the output. - For the saddle , find both partial derivatives at . Is a minimum?
Show answer
and . It is not a minimum: , but . - A model has weights. How many loss evaluations does a central-difference gradient check need?
Show answer
Two per weight: evaluations, which is why it is used mainly for debugging, on small models.
Next: P1.C5 puts the partial derivatives into one vector, the gradient, and shows that it points in the direction in which the function rises fastest. P1.C3 (the chain rule) is what lets us compute the partial derivatives of a loss that has functions inside functions, which is backpropagation.