Softmax Cross-Entropy Gradient

medium
Unit 9 · Backprop & Regularization0/3 to milestone

The gradient of the softmax + cross-entropy loss with respect to the logits is beautifully simple:

∂L∂z=1N(softmax(z)−onehot(y))\frac{\partial \mathcal{L}}{\partial z} = \frac{1}{N}\left(\text{softmax}(z) - \text{onehot}(y)\right)

Implement loss_and_grad(logits, labels) for logits of shape (N, C) and integer labels, returning (loss, grad), where loss is the mean cross-entropy and grad has the same shape as logits. Make it numerically stable.

Then implement numerical_grad(f, x, eps=1e-6): the central-difference gradient of a scalar function f at array x, perturbing each element by ±eps. It's the standard way to check a hand-written gradient.

#backprop#gradients#numpy2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Softmax Cross-Entropy Gradient · TechGradify