v9.1.1
Menu

Softmax Cross-Entropy Gradient

mediumPROBackpropagationDeep LearningCV: Deep Learning

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:

  1. Compute the softmax of the input vector zz using the formula pi=ezi∑jezjp_i = \frac{e^{z_i}}{\sum_j e^{z_j}}.
  2. Calculate the cross-entropy loss using L=−∑iyilog⁡(pi)L = -\sum_i y_i \log(p_i), where yy is the one-hot encoded target vector. The key formula for the gradient is:
∂L∂zi=pi−yi\frac{\partial L}{\partial z_i} = p_i - y_i

This technique is widely used in image classification tasks.

Example

Input
logits = [[1.0, 2.0, 3.0]]  # batch=1, classes=3
targets = [2]  # True class is index 2
Output
[[0.09, 0.24, -0.33]]
Reasoning
  • Inputs: logits is a 1×31 \times 3 batch — one sample with raw scores z=(1,2,3)z = (1, 2, 3) for classes 0, 1, 2. targets is [2]: the true class of that sample is index 2, so its one-hot vector is y=(0,0,1)y = (0, 0, 1).
  • Softmax: exponentiate each score: e1≈2.7183e^1 \approx 2.7183, e2≈7.3891e^2 \approx 7.3891, e3≈20.0855e^3 \approx 20.0855, which sum to ≈30.1929\approx 30.1929. Dividing gives p≈(0.0900,0.2447,0.6652)p \approx (0.0900, 0.2447, 0.6652) — positive and summing to 1.
  • Gradient: apply ∂L∂zi=pi−yi\frac{\partial L}{\partial z_i} = p_i - y_i. Classes 0 and 1 have yi=0y_i = 0, so they keep 0.09000.0900 and 0.24470.2447; class 2 gets 0.6652−1=−0.33480.6652 - 1 = -0.3348.
  • Output: a 1×31 \times 3 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 1−1=01 - 1 = 0. 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

Learn this in

More from CV: Deep Learning

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.