Skip to content
mlmentorship

Cross-Entropy From Logits

Compute mean multiclass cross-entropy from logits and integer labels.

Published · 13 min read ·Role-specific ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Cross-Entropy From Logits

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

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

The declared target selects a probability, not a new predictionTurn 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.One distribution; the declared targetselects lossLogits 2, 0; one sharedpredictionClass 0: 88.08%0.881Target 0Loss 0.127Class 1: 11.92%0.119Target 1Loss 2.127Same probabilities. A differenttarget selects a different loss.
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?
Full interview answer 13 min read
Reading depth

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.
exampleclass 0class 1class 2label
02100
10121
example / row 0
0
class 0 / row 0
2
class 1 / row 0
1

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

The declared target selects a probability, not a new predictionTurn 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.One distribution; the declared targetselects lossLogits 2, 0; one sharedpredictionClass 0: 88.08%0.881Target 0Loss 0.127Class 1: 11.92%0.119Target 1Loss 2.127Same probabilities. A differenttarget selects a different loss.
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.
exampleclass 0class 1class 2label
02100
10121
example / row 0
0
class 0 / row 0
2
class 1 / row 0
1

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.

Code

import numpy as np

def cross_entropy(logits: np.ndarray, labels: np.ndarray) -> float:
   shifted = logits - np.max(logits, axis=1, keepdims=True)
   log_normalizer = np.log(np.sum(np.exp(shifted), axis=1))
   correct_logits = shifted[np.arange(len(labels)), labels]
   return float(np.mean(log_normalizer - correct_logits))

Cost: 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.