U-Net's Energy: Pixel-Wise Soft-Max and Weighted Cross-Entropy
U-Net is trained with a soft-max over the channels at every pixel of its last feature map and a cross-entropy in which every pixel has its own weight. Compute this energy and its gradient with respect to the activations.
Implement unet_energy(logits, labels, weights).
Inputs
logits: array of shape (K,H,W); ak(x) is the activation of channel k at pixel x.
labels: integer array (H,W) with the true class ℓ(x)∈{0,…,K−1}.
weights: array (H,W) with the weight w(x)≥0 of each pixel.
Definitions
pk(x)=∑k′=0K−1exp(ak′(x))exp(ak(x)),E=−∑xw(x)logpℓ(x)(x).
The energy is a sum over pixels, not a mean.
Output: a tuple (E, grad) with E a Python float and grad the array ∂E/∂ak(x) of shape (K,H,W).
Notes
- Activations can be as large as ±1000: compute without overflow and without taking the log of 0.
- The paper prints the energy without the minus sign; the minus sign makes E≥0, the quantity that gradient descent minimises.