#303Log-softmaxEasyNeural NetworksActivation FunctionsLoss Functions
Log-softmax
Background
Log-softmax computes in a numerically stable way. It appears everywhere softmax and log show up together — cross-entropy loss, log-likelihoods, beam search — because computing them jointly avoids the overflow of exp on large logits and the underflow on tiny probabilities.
Problem statement
Implement log_softmax(x) over the last axis:
The max-subtraction is the stability trick; it cancels mathematically but prevents overflow.
Input
x—np.ndarray: 1-D logits, or 2-D(batch, classes)(softmax taken over the last axis).
Output
Returns an np.ndarray of the same shape: the log-probabilities (each row's exp sums to 1).
Examples
Example 1
Input: x = [1, 2, 3]
Output: [-2.4076, -1.4076, -0.4076]
Explanation: subtract the max () to get , then subtract .
Constraints
- Subtract the per-row max before exponentiating (numerical stability).
- Operate over the last axis; support both 1-D and 2-D inputs.
exp(log_softmax(x))must sum to 1 along the last axis; tests useatol=1e-6.
Notes
- ; never compute
log(softmax(x))as two separate steps — the intermediate softmax can underflow to 0. - Cross-entropy loss is just , which is why frameworks fuse the two operations.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference example: 1-D logits
- •Sample 2-D batch
- •Example with large logits for stability