Compute stable log-normalizers per example, subtract the indexed correct logits, then average example losses.
Problem trace
The declared target selects a probability, not a new prediction
Read it this way:Turn the two logits into one shared probability distribution. The declared target selects which probability is scored. A likely target has small loss; an unlikely target has larger loss. Changing only the target does not recompute the probabilities. Batch loss averages the per-example losses. This example keeps logits fixed and changes only the label. With logits fixed, which quantity changes when the target changes from class zero to class one?
Sources and provenance
Full interview answer 13 min read
Compute the average categorical prediction loss from a batch of raw class scores and correct class labels.
Problem
Input. Float64 logits with shape (batch, classes) and integer labels with shape (batch,).
Output. Return one floating-point mean negative log-probability for the labeled classes, using natural logarithms.
Each row’s class probabilities are its softmax distribution; the input scores are not already probabilities.
Rules. Both dimensions are positive, and every label is a valid zero-based class index.
Require finite logits with representable differences. Repeated labels are valid; preserve both inputs.
Empty means and ignored labels are outside this reference contract.
Example. Logits [[0, 0], [0, 0]] and labels [0, 1] return approximately 0.693147.
Each correct class has probability one half, so both observations contribute the same loss.
Picture
For logits [[2,1,0],[0,1,2]] and labels [0,1], losses are approximately 0.407606 and 1.407606.
Their mean is approximately 0.907606.
Each label selects its own row, not a shared column slice.
Problem trace
Separate multiclass batch: stabilize, select correct logits, and average losses
Input and goalCompute mean multiclass cross-entropy from logits and integer labels.
Read logits and integer labelsUse logits [[2,1,0],[0,1,2]] with labels [0,1]. Each label selects one class in its own row.
example
class 0
class 1
class 2
label
0
2
1
0
0
1
0
1
2
1
example / row 0
0
class 0 / row 0
2
class 1 / row 0
1
Shift each row by its maximumBoth row maxima are 2. Shifted rows become [0,-1,-2] and [-2,-1,0], keeping the selected entries 0 and -1.
example
class 0
class 1
class 2
label
0
0
-1
-2
0
1
-2
-1
0
1
maxima[2,2]
maxima
not shown→[2,2]
class 0 / row 0
2→0
class 1 / row 0
1→-1
Compute row log-normalizersEach shifted row has exponential sum 1 + 0.3679 + 0.1353 = 1.5032, so log_normalizer = log(1.5032) = 0.4076.
example
exp sum
log normalizer
0
1.5032
0.4076
1
1.5032
0.4076
maxima
[2,2]→not shown
exp sum / row 0
0→1.5032
log normalizer / row 0
-1→0.4076
Subtract each selected logitExample 0 loss is 0.4076 - 0 = 0.4076. Example 1 label 1 selects shifted logit -1, so loss is 0.4076 - (-1) = 1.4076.
example
normalizer
correct shifted logit
loss
0
0.4076
0
0.4076
1
0.4076
-1
1.4076
normalizer / row 0
1.5032→0.4076
correct shifted logit / row 0
0.4076→0
loss / row 0
not shown→0.4076
Average the batchMean cross-entropy = (0.4076 + 1.4076) / 2 = 0.9076.
example
loss
0
0.4076
1
1.4076
mean
0.9076
arithmetic1.8152 / 2 = 0.9076resultmean = 0.9076
arithmetic
not shown→1.8152 / 2 = 0.9076
result
not shown→mean = 0.9076
loss / row 1
0.4076→1.4076
Recognize it
Use it when multiclass logits and integer labels require negative log likelihood without explicitly forming potentially unstable probabilities.
Keep true
For each row, log_normalizer minus the shifted selected logit equals negative log probability of the label; max shifting cancels from both terms.
Reuse it
For stable classification losses, compute log-normalization in score space, gather the target score by aligned row indices, and reduce only after producing per-example losses.
Use logits [[2,1,0],[0,1,2]] with labels [0,1]. Each label selects one class in its own row. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why do equal normalizers produce losses 0.4076 and 1.4076 for the two rows?
Reference drawing
Problem trace
The declared target selects a probability, not a new prediction
Execution trace
Input and goalCompute mean multiclass cross-entropy from logits and integer labels.
Read logits and integer labelsUse logits [[2,1,0],[0,1,2]] with labels [0,1]. Each label selects one class in its own row.
example
class 0
class 1
class 2
label
0
2
1
0
0
1
0
1
2
1
example / row 0
0
class 0 / row 0
2
class 1 / row 0
1
Shift each row by its maximumBoth row maxima are 2. Shifted rows become [0,-1,-2] and [-2,-1,0], keeping the selected entries 0 and -1.
example
class 0
class 1
class 2
label
0
0
-1
-2
0
1
-2
-1
0
1
maxima[2,2]
maxima
not shown→[2,2]
class 0 / row 0
2→0
class 1 / row 0
1→-1
Compute row log-normalizersEach shifted row has exponential sum 1 + 0.3679 + 0.1353 = 1.5032, so log_normalizer = log(1.5032) = 0.4076.
example
exp sum
log normalizer
0
1.5032
0.4076
1
1.5032
0.4076
maxima
[2,2]→not shown
exp sum / row 0
0→1.5032
log normalizer / row 0
-1→0.4076
Subtract each selected logitExample 0 loss is 0.4076 - 0 = 0.4076. Example 1 label 1 selects shifted logit -1, so loss is 0.4076 - (-1) = 1.4076.
example
normalizer
correct shifted logit
loss
0
0.4076
0
0.4076
1
0.4076
-1
1.4076
normalizer / row 0
1.5032→0.4076
correct shifted logit / row 0
0.4076→0
loss / row 0
not shown→0.4076
Average the batchMean cross-entropy = (0.4076 + 1.4076) / 2 = 0.9076.
example
loss
0
0.4076
1
1.4076
mean
0.9076
arithmetic1.8152 / 2 = 0.9076resultmean = 0.9076
arithmetic
not shown→1.8152 / 2 = 0.9076
result
not shown→mean = 0.9076
loss / row 1
0.4076→1.4076
Recognize it
Use it when multiclass logits and integer labels require negative log likelihood without explicitly forming potentially unstable probabilities.
Keep true
For each row, log_normalizer minus the shifted selected logit equals negative log probability of the label; max shifting cancels from both terms.
Reuse it
For stable classification losses, compute log-normalization in score space, gather the target score by aligned row indices, and reduce only after producing per-example losses.
Use logits [[2,1,0],[0,1,2]] with labels [0,1]. Each label selects one class in its own row. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why do equal normalizers produce losses 0.4076 and 1.4076 for the two rows?
Read it this way:Turn the two logits into one shared probability distribution. The declared target selects which probability is scored. A likely target has small loss; an unlikely target has larger loss. Changing only the target does not recompute the probabilities. Batch loss averages the per-example losses. This example keeps logits fixed and changes only the label. With logits fixed, which quantity changes when the target changes from class zero to class one?
The cross-entropy owner derives the likelihood and gradient.
Subtracting the same row maximum from every logit preserves probabilities while preventing positive exponential arguments.
Cost:O(batch×classes) arithmetic and temporary storage, despite the scalar result.
Change the Requirement
Weight the Examples
New task: Return a weighted mean using nonnegative finite weights with a positive representable total.
Picture and change: Keep per-row losses until weighting; divide by weight sum rather than batch size.
Code: Retain the original logits and label contract.
def weighted_cross_entropy(logits, labels, weights) -> float: weights = np.asarray(weights, dtype=np.float64) if weights.shape != labels.shape or np.any(~np.isfinite(weights)) or np.any(weights < 0): raise ValueError("weights must match labels and be finite and nonnegative") total = weights.sum() if not np.isfinite(total) or total <= 0: raise ValueError("weight total must be positive and representable") shifted = logits - logits.max(axis=1, keepdims=True) normalizer = np.log(np.exp(shifted).sum(axis=1)) losses = normalizer - shifted[np.arange(len(labels)), labels] return float(np.sum(losses * (weights / total)))
Check: Weights [3,1] change the example mean to approximately 0.657606; [0,0] raises ValueError.
Use when: Example weights define the intended reporting or training population.
Ignore Selected Labels
New task: Exclude rows with label -1 from the mean.
Picture and change: Filter both logits and labels before gathering or reducing.
Code: Nonignored labels retain the valid class-index range.
def cross_entropy_ignoring(logits, labels, ignored: int = -1) -> float: valid = labels != ignored if not np.any(valid): raise ValueError("mean loss needs at least one retained example") return cross_entropy(logits[valid], labels[valid])
Check: Ignoring the second row leaves loss approximately 0.407606; ignoring both rows raises ValueError.
Use when: Padding is not a labeled observation.
Boolean selection allocates copies; both alternatives retain linear-in-logits time and storage bounds.
Reconstruct
Why not pass ignored negative labels directly to the reference?
Reasoned answer
NumPy treats -1 as the last column index, not an ignore instruction.
For the first example row, this silently selects class two and gives approximately 2.407606 instead of excluding the example.
The gathering operation cannot infer the meaning of a sentinel.
Define filtering and the empty-result policy before evaluating the reduction.