Implement softmax and cross-entropy loss from scratch
Written by the mlprep team · Updated
Implement softmax and cross-entropy loss in NumPy. Then tell me: what goes wrong with the naive implementation, and how do you fix it?
Naive implementation (and why it breaks)#
import numpy as np
def softmax_naive(x):
return np.exp(x) / np.sum(np.exp(x))
def cross_entropy_naive(logits, target):
probs = softmax_naive(logits)
return -np.log(probs[target])This works for small values but overflows for large inputs:
softmax_naive(np.array([1000.0, 1001.0, 1002.0]))
# RuntimeWarning: overflow encountered in exp
# array([nan, nan, nan])exp(1000) exceeds float64 range (~1.8 × 10³⁰⁸), producing inf. inf / inf is nan.
The fix: subtract the max (log-sum-exp trick)#
Softmax is shift-invariant: softmax(x) == softmax(x - c) for any constant c. Proof:
exp(x_i - c) / Σ exp(x_j - c)
= exp(x_i) * exp(-c) / (Σ exp(x_j) * exp(-c))
= exp(x_i) / Σ exp(x_j)
Set c = max(x). Now the largest value fed to exp is 0, and all others are negative. No overflow.
def softmax(x):
x = x - np.max(x) # shift for numerical stability
exp_x = np.exp(x)
return exp_x / np.sum(exp_x)Cross-entropy: avoid log(0)#
def cross_entropy(logits, target):
probs = softmax(logits)
return -np.log(probs[target] + 1e-8) # naive fix, but wrongAdding 1e-8 works but introduces a tiny bias. The clean fix: compute log-softmax directly, avoiding the instability of log(softmax(x)) when probabilities are tiny.
def log_softmax(x):
x = x - np.max(x)
return x - np.log(np.sum(np.exp(x)))
def cross_entropy(logits, target):
return -log_softmax(logits)[target]This is numerically exact because we never compute exp then log — we stay in log-space throughout.
Batch version#
def softmax_batch(x):
# x shape: (batch, classes)
x = x - x.max(axis=1, keepdims=True)
exp_x = np.exp(x)
return exp_x / exp_x.sum(axis=1, keepdims=True)
def cross_entropy_batch(logits, targets):
# targets shape: (batch,) — integer class indices
log_probs = logits - logits.max(axis=1, keepdims=True)
log_probs -= np.log(np.exp(log_probs).sum(axis=1, keepdims=True))
return -log_probs[np.arange(len(targets)), targets].mean()The keepdims=True is essential — without it, broadcasting breaks for the batch subtraction.
Interview red flags#
- Writing exp(x) / sum(exp(x)) with no max subtraction, which overflows to NaN for large logits.
- Computing log(softmax(x)) as two steps and patching log(0) with a + 1e-8 epsilon instead of using log-softmax.
- Feeding probabilities rather than logits into a loss that expects logits, which double-applies the sigmoid or softmax.
- Being unable to state the softmax + cross-entropy gradient: ŷ − y.
Your cross-entropy implementation handles multi-class classification. How would you modify it for binary classification, and is there a numerical stability issue there too?
Binary cross-entropy#
For binary classification, the loss is:
BCE = -[y * log(p) + (1 - y) * log(1 - p)]
where p = sigmoid(logit) and y ∈ {0, 1}.
Naive implementation#
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def binary_cross_entropy_naive(logit, y):
p = sigmoid(logit)
return -(y * np.log(p) + (1 - y) * np.log(1 - p))Problem: for logit = -100, sigmoid(-100) ≈ 3.7e-44, and log(3.7e-44) = -100 — fine mathematically. But floating point can underflow: sigmoid(-100) rounds to 0.0, and log(0.0) = -inf.
Numerically stable form#
Expand log(sigmoid(x)) directly:
log(sigmoid(x)) = log(1 / (1 + exp(-x)))
= -log(1 + exp(-x))
= -softplus(-x)
PyTorch's softplus is computed as log(1 + exp(x)) with its own stability tricks. Substituting:
def binary_cross_entropy(logit, y):
# Stable: -[y*x - log(1 + exp(x))]
# Equivalent rearrangement that avoids overflow for large positive x
# and underflow for large negative x
return np.maximum(logit, 0) - logit * y + np.log(1 + np.exp(-np.abs(logit)))This formula handles both extremes:
- Large positive
logit:np.exp(-np.abs(logit))→ 0, result ≈logit - logit * y - Large negative
logit:np.maximum(logit, 0)→ 0, result ≈-logit * y + log(1 + small)≈-logit * y
Vectorized batch version#
def binary_cross_entropy_batch(logits, targets):
# logits, targets: shape (batch,)
loss = (np.maximum(logits, 0)
- logits * targets
+ np.log(1 + np.exp(-np.abs(logits))))
return loss.mean()This is exactly what torch.nn.BCEWithLogitsLoss does internally — it takes raw logits rather than probabilities specifically to apply this stable formula.
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
Naive softmax overflows for large logits (exp(1000) = inf). Fix: subtract max before exponentiation — softmax is shift-invariant so this doesn't change the output. For cross-entropy, compute log-softmax directly in log-space rather than log(softmax(x)) to avoid log(0). Binary cross-entropy has the same issue: use the max(x,0) - x*y + log(1+exp(-|x|)) form that PyTorch's BCEWithLogitsLoss uses internally.
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- How would you implement the backward pass for softmax cross-entropy? What's the surprisingly clean form of the gradient?
- What is label smoothing and how do you modify the cross-entropy loss to implement it?
- If you were implementing this in a production training loop, what would you do differently from a pure NumPy implementation?
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions
Implement k-nearest neighbors with efficient distance computation
Implement scaled dot-product attention from scratch
Implement gradient descent for linear regression from scratch
Explain cross-entropy loss — binary vs categorical, and why it works for classification