r/learnmachinelearning • u/CelebrityChess • 21d ago
Help why is the gradient of softmax plus cross entropy just p minus y?
i was working through backprop by hand for a tiny classifier and the gradient with respect to the logits came out as predicted probs minus the one-hot label. it's so clean that it feels like i must have made an error, because softmax has that ugly jacobian with p_i(delta_ij - p_j) in it.
i can follow the algebra when i write it all out but i don't see why the mess cancels. is there a reason it works out like that, or is it just a lucky coincidence of using log loss with softmax?
2
Upvotes
2
u/Ecstatic-Ring3057 20d ago
Not a coincidence: the log in cross-entropy undoes the exp in softmax, so the loss is just logsumexp(z) minus z_y, and the gradient of logsumexp is the softmax itself. Sigmoid with log loss gives p minus y for the same reason
1
u/MolassesLate4676 21d ago
What do you mean by you can’t see why the mess cancels? What mess?
Like how does the gradient get constructed from one-hot on p?
1
u/sinea17 21d ago
For logits z and true class t, try writing the loss as L = log(sum(exp(z))) - z_t. The log-normalizer's gradient is p and the true-class term contributes -y, so the clean result comes from this particular pairing; you don't need to expand the softmax Jacobian.