ML MATH & LINEAR ALGEBRA Β· INTERVIEW QUESTION
Derive the gradient of the cross-entropy loss for softmax output.
π΄ advanced Β· Calculus & Optimization
Hint: Start with the softmax function, write the cross-entropy loss, and use the quotient rule.
Answer
Softmax function:
Cross-entropy loss:
The gradient has an elegant form:
This comes from the Jacobian of softmax:
where is the Kronecker delta. Substituting into the chain rule and using gives the compact form.
This is why softmax + cross-entropy is preferred: the gradient is simply the difference between predicted and true probabilities.
python
import numpy as np
def softmax(z):
exp_z = np.exp(z - np.max(z)) # numerical stability
return exp_z / exp_z.sum()
def cross_entropy_grad(z, y_true):
p = softmax(z)
return p - y_true # elegant!Related questions
- What is the difference between convex and non-convex optimization? Why does it matter in deep learning?
- What are gradients, Jacobians, and Hessians? When do you use each in ML?
- What is gradient descent? Explain the intuition behind it.
- What is the vanishing/exploding gradient problem? How do modern architectures solve it?
- Explain learning rate scheduling strategies. Which are most effective?