Partial Derivatives of a Model Loss, Worked by Hand
Compute the gradients of linear and logistic regression losses step by step, check them numerically and turn them into training updates.
Key takeaways
- A partial derivative treats every other quantity, including the data and other parameters, as a constant.
- For squared error on a linear model, the gradient is the prediction error times the input.
- For logistic regression with cross-entropy loss, the gradient with respect to the score is the predicted probability minus the label.
- Over a data set, average the per-example gradients if the loss is an average.
- A central finite difference is a cheap and reliable check on a hand-derived gradient.
A partial derivative of a loss tells you how fast the loss changes when you nudge one parameter and hold the others fixed. Collect one for every parameter and you have the gradient, the vector that training uses to decide how to move.
You only need a few calculus rules to compute these by hand for the basic models. Doing it once, with real numbers, makes the output of any automatic tool much easier to trust and to debug.
Setting up the problem
Take the smallest useful model: one input x, a weight w and a bias b.
prediction ŷ = w x + b
loss L = ½ (ŷ − y)² The factor ½ is a convenience that cancels the 2 produced by differentiating the square. It halves the gradient, which you can absorb into the learning rate.
During training, x and y are fixed data. The variables are w and b. This is the opposite of school algebra, where x is usually the unknown.
Differentiating squared error
Name the error e = ŷ − y, so L = ½e². The chain rule says to multiply the rate of change at each link.
∂L/∂e = e derivative of ½e²
∂e/∂w = x e = w x + b − y
∂e/∂b = 1
∂L/∂w = e · x = (ŷ − y) x
∂L/∂b = e = (ŷ − y) The structure is worth remembering: error times input. A large error on a large input pushes its weight hard. An input of zero gives that weight no signal from this example.
Putting in numbers
Let x = 2, y = 7, w = 1.5 and b = 1.
ŷ = 1.5 · 2 + 1 = 4
e = 4 − 7 = −3
L = ½ · 9 = 4.5
∂L/∂w = −3 · 2 = −6
∂L/∂b = −3 Both derivatives are negative, so increasing either parameter lowers the loss. Gradient descent subtracts the learning rate times the gradient. With η = 0.1:
w ← 1.5 − 0.1 · (−6) = 2.1
b ← 1.0 − 0.1 · (−3) = 1.3
new ŷ = 2.1 · 2 + 1.3 = 5.5
new L = ½ · (5.5 − 7)² = 1.125 The loss fell from 4.5 to 1.125. Compute both derivatives at the old values before updating either parameter.
Checking with finite differences
The derivative is a limit of small differences, so you can test it. Nudge w by h = 0.001 in both directions.
L(w = 1.501) = ½ · (4.002 − 7)² = 4.494002
L(w = 1.499) = ½ · (3.998 − 7)² = 4.506002
(4.494002 − 4.506002) / 0.002 = −6.000 This central difference matches the formula. It is far more accurate than nudging in one direction only, which here would give −5.998. In code, use double precision and a small h such as 10⁻⁵ or 10⁻⁶. A step that is too small loses accuracy to rounding.
Averaging over examples
A training loss is usually the average over n examples. The derivative of an average is the average of the derivatives.
Keep w = 1.5 and b = 1, with examples (1, 3), (2, 7) and (3, 7).
| x | y | ŷ | e | e · x |
|---|---|---|---|---|
| 1 | 3 | 2.5 | −0.5 | −0.5 |
| 2 | 7 | 4 | −3 | −6 |
| 3 | 7 | 5.5 | −1.5 | −4.5 |
The gradient for w is (−11)/3 ≈ −3.67, and for b it is (−5)/3 ≈ −1.67. If your library sums instead of averaging, the gradient is n times larger and your learning rate effectively changes with batch size.
With many features, X of shape (n, d) and w of shape (d,), the same pattern reads compactly.
∇_w L = (1/n) Xᵀ (ŷ − y) shape (d,)
∂L/∂b = (1/n) Σ (ŷ_i − y_i) Logistic regression
For a label y that is 0 or 1, compute a score z = wx + b, turn it into a probability p = σ(z) = 1/(1 + e^(−z)), and use cross-entropy with the natural logarithm.
L = −[ y ln p + (1 − y) ln(1 − p) ]
∂L/∂p = (p − y) / (p (1 − p))
∂p/∂z = p (1 − p)
∂L/∂z = p − y the product cancels neatly
∂L/∂w = (p − y) x
∂L/∂b = (p − y) Try x = 2, y = 1, w = 0.5 and b = −1. The score is 0, so p = 0.5 and L = ln 2 ≈ 0.693. The gradients are ∂L/∂w = −1 and ∂L/∂b = −0.5.
With η = 0.1 the new values are w = 0.6 and b = −0.95. The score becomes 0.25, p ≈ 0.562 and L ≈ 0.576.
Again the form is error times input. This is no coincidence for a standard pairing of output function and loss, explored in cross-entropy from likelihood. The full model is described in logistic regression.
Three or more classes
With several classes, the model produces one score per class and the softmax turns scores into probabilities: p_k = exp(z_k) divided by the sum of all the exponentials. The loss is −ln of the probability given to the true class.
The derivative with respect to each score is p_k − y_k, where y_k is 1 for the true class and 0 otherwise.
scores z = (2, 1, 0), true class is the second
exponentials ≈ (7.389, 2.718, 1.000), sum ≈ 11.107
probabilities p ≈ (0.665, 0.245, 0.090)
loss = −ln 0.245 ≈ 1.408
∂L/∂z = p − y ≈ (0.665, −0.755, 0.090) The entries sum to zero. A descent step raises the true class score and lowers the others, the most confident wrong class the most. For a linear model with scores z = Wx + b, the gradient for W is the outer product (p − y)xᵀ, with one row per class. Softmax regression covers the model.
One hidden unit
Add a layer and the same rules still apply, one link at a time. Let h = ReLU(wx + b), where ReLU keeps positive values and replaces negative ones with zero, and let ŷ = vh + c with loss ½(ŷ − y)².
Take x = 2, w = 0.5, b = 0, v = 3, c = 0 and y = 1.
h = ReLU(1) = 1 ŷ = 3 e = 2
∂L/∂v = e · h = 2
∂L/∂c = e = 2
∂L/∂w = e · v · 1 · x = 12 (ReLU slope is 1 here)
∂L/∂b = e · v · 1 = 6 The gradient for the early weight includes the later weight v, because its effect reaches the loss through v. If wx + b were negative, the ReLU slope would be 0 and neither w nor b would receive any signal from this example. A unit stuck that way on all examples stops learning through this path.
Adding a penalty
With an L2 penalty (λ/2)‖w‖², the gradient with respect to the weights gains the term λw. The bias is usually left out of the penalty.
∇_w L = (1/n) Xᵀ (ŷ − y) + λ w An absolute value penalty λ|w| has derivative λ · sign(w) away from zero and no derivative at zero. There you use a subgradient, any value between −λ and λ, or a proximal step. The absolute error loss |ŷ − y| has the same kink at zero error.
Checking a gradient in code
The function below compares the analytic gradient with central differences for linear regression.
import numpy as np
X = np.array([[1.0], [2], [3]]) # (3, 1)
y = np.array([3.0, 7, 7]) # (3,)
theta = np.array([1.5, 1.0]) # weight, bias
def loss(t):
return 0.5 * np.mean((X[:, 0] * t[0] + t[1] - y) ** 2)
e = X[:, 0] * theta[0] + theta[1] - y
analytic = np.array([np.mean(e * X[:, 0]), np.mean(e)])
h = 1e-5
numeric = np.array([(loss(theta + h * u) - loss(theta - h * u)) / (2 * h)
for u in np.eye(2)])
print(analytic, numeric) # both about [-3.667, -1.667] Finite differences need two loss evaluations per parameter, so they are for testing, not training large models. Automatic differentiation computes exact derivatives of the program efficiently.
Reading the size of a gradient
The error-times-input form shows that feature units leak into gradients. Multiply a feature by 100 and, for the same predictions, its weight must be 100 times smaller while its partial derivative becomes 100 times larger. A single learning rate then suits one weight badly.
Standardizing features from training statistics puts the partial derivatives on comparable footing. Gradient size also depends on how wrong the model currently is, so it normally changes during training.
A small gradient does not by itself show that a parameter is unimportant. It says that a tiny change would barely alter the loss at the current point. The weight might matter a great deal if removed entirely, or its effect might be flat only because a saturated function sits downstream. Positive and negative contributions from different examples can also cancel in the average.
For debugging, print the gradient for a single example you can compute on paper. Then compare a batch gradient with the average of the single-example gradients. If they differ, look for an unintended sum, a wrong axis or a layer that mixes examples.
Common mistakes
- A flipped sign. Writing y − ŷ for the error and still subtracting the gradient makes the loss climb.
- A dropped input. The derivative for the weight needs the factor x.
- Updating in sequence. Changing w and then using the new w to compute the gradient for b is a different algorithm.
- Mismatched reductions. Mixing a summed loss with an averaged gradient fails the numerical check by a factor of n.
- Checking at a kink. Finite differences straddling a ReLU or absolute value corner will disagree even if your code is right.
Common questions
What if the gradient is zero?
You are at a stationary point. For convex losses such as those above, that is a minimum, if one exists. For nonconvex models it may be a saddle point or a flat region.
Does the gradient point toward the minimum?
Its negative points in the direction of steepest local decrease under the Euclidean measure. In a stretched valley that can be far from the direction to the minimum.
Why differentiate with respect to inputs?
Training does not change the data, but input gradients show how sensitive a prediction is and are used in attribution and robustness testing. The same rules apply: ∂ŷ/∂x = w for the linear model.