---
title: Numerically stable softmax and cross-entropy
url: https://gurkanozkan.ai/learn/coding/mle-numerically-stable-softmax-and-cross-entropy-08/
markdown: https://gurkanozkan.ai/learn/coding/mle-numerically-stable-softmax-and-cross-entropy-08.md
kind: coding
difficulty: Easy
topics:
  - NumPy
  - Numerical stability
  - Loss functions
json: https://gurkanozkan.ai/api/learn/coding/mle-numerically-stable-softmax-and-cross-entropy-08.json
robots: noindex
---

# Numerically stable softmax and cross-entropy

`logits` has shape (N, C); `labels` holds N integer class indices. Return `(probs, mean_loss)`: the row-wise softmax probabilities and the mean negative log-likelihood. It must stay finite for logits up to ±1000.

## Signature

```python
def softmax_cross_entropy(logits: list[list[float]], labels: list[int]) -> tuple[np.ndarray, float]: ...
```

## Examples

Each call and the value it should give.

```python
>>> close(softmax_cross_entropy([[0.0, 0.0]], [1]), ([[0.5, 0.5]], 0.693147))
True

>>> close(softmax_cross_entropy([[1000.0, 1000.0]], [0]), ([[0.5, 0.5]], 0.693147))
True
```

## Hints

1. Subtract the row max before exp — avoid overflow.
2. log probabilities as (z - max) - log(sum(exp(z - max))); loss is the negative mean of the label term.
3. Use fancy indexing for the label terms; the mean is over examples, not classes.

## Reference solution

```python
import numpy as np

def softmax_cross_entropy(logits, labels):
    z = np.asarray(logits, dtype=float)
    z = z - z.max(axis=1, keepdims=True)
    logp = z - np.log(np.exp(z).sum(axis=1, keepdims=True))
    p = np.exp(logp)
    loss = -logp[np.arange(len(labels)), labels].mean()
    return p, float(loss)
```

## What a strong solution covers

- Subtracts the row max (log-sum-exp).
- Computes the loss from log-probabilities rather than log(softmax).
- Uses fancy indexing for the label terms.
- States the gradient `softmax − one_hot`.

## Common mistakes

- `np.log(np.exp(z).sum())` overflowing
- averaging over classes instead of examples.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
