How do you derive the gradient of the softmax cross-entropy loss with respect to the logits?

Deep learning, Backpropagation
Level L3 Intermediate. Length Short. Nature Mat Mathematical.

What's being asked

Whether you can do a basic and very common derivation. It tests careful use of the chain rule and indices.

Key idea

Let z be the logits (the raw scores before softmax), p=softmax⁡(z) and y a one-hot label (1 for the true class, 0 elsewhere). The loss L=−∑kyklog⁡pk has gradient ∂L∂z=p−y.

Steps

  1. Write pk=ezk/∑jezj and L=−∑kyklog⁡pk.
  2. Simplify first, because it avoids the full softmax Jacobian: log⁡pk=zk−log⁡∑jezj, so L=−∑kykzk+log⁡∑jezj (using ∑kyk=1).
  3. Differentiate: ∂L/∂zi=pi−yi.
  4. Interpret: the gradient is the prediction error. It is bounded, which is one reason this pairing trains well.
  5. Mention numerical stability: subtract max⁡jzj before exponentiating (the log-sum-exp trick). This stops ezj from overflowing and does not change p.

Common mistakes

How long your answer should be

Under 2 minutes; four lines.

Last checked on 4 December 2026.

Read this

Previous in Deep learning: A tiny network has input x=(1,2), two hidden units with h1=ReLU⁡(x1+x2−2) and h2=ReLU⁡(−x1+x2−2), and a linear output y^=2h1+3h2+1. Here ReLU⁡(z)=max⁡(0,z). Compute the hidden values, the output y^, and the squared error (y^−y)2 for the target y=5?
Next in Deep learning: Suppose you train a binary classification network with a sigmoid output using mean-squared error (MSE) instead of cross-entropy. Is training still useful, judging by the gradient of each loss with respect to the logit z (the input to the sigmoid)? How do the two losses look as functions of z for a positive example?