Softmax Cross-Entropy Gradient
Implement a function to compute the gradient of the cross-entropy loss with softmax activation, a crucial component in backpropagation for training deep neural networks. This task involves understanding the mathematical foundations of softmax and cross-entropy loss.
The softmax function is used for multi-class classification problems, where it maps a vector of real numbers to a vector of probabilities, ensuring that each element is in the range (0, 1) and the elements sum up to 1. The cross-entropy loss measures the difference between the predicted probabilities and the true distribution, typically represented as a one-hot encoded vector.
To compute the gradient, we follow these steps:
- Compute the softmax of the input vector using the formula .
- Calculate the cross-entropy loss using , where is the one-hot encoded target vector. The key formula for the gradient is:
This technique is widely used in image classification tasks.
Example
logits = [[1.0, 2.0, 3.0]] # batch=1, classes=3 targets = [2] # True class is index 2
[[0.09, 0.24, -0.33]]
- Inputs:
logitsis a batch — one sample with raw scores for classes 0, 1, 2.targetsis[2]: the true class of that sample is index 2, so its one-hot vector is . - Softmax: exponentiate each score: , , , which sum to . Dividing gives — positive and summing to 1.
- Gradient: apply . Classes 0 and 1 have , so they keep and ; class 2 gets .
- Output: a grid of floats, same shape as
logits, shown rounded as[[0.09, 0.24, -0.33]]. - Notice: the only negative entry sits at the true class (gradient descent pushes its score up), and each row sums to . Every sample in a batch is handled independently, with no averaging over the batch.
Constraints
- logits: Raw network outputs (batch_size, num_classes)
- targets: Ground truth class indices (batch_size,)
- Return: Gradient tensor same shape as logits