3.3 Softmax Regression Implementation
Just as we implemented linear regression both from scratch and concisely in Chapter 2, we now build softmax regression on Fashion-MNIST both ways. We start from raw tensors—implementing the rowwise softmax, vectorized cross-entropy loss, and SoftmaxRegressionScratch parameters () alongside the reusable Classifier(d2l.Module) base class—train to roughly validation accuracy, and inspect what the linear model learned through its confusion matrix and weight templates. In Section 3.3.5, we then replace manual tensors and probability clamping with a built-in linear layer and a shifted log-sum-exp cross-entropy loss computed directly from raw logits, eliminating floating-point overflow and underflow at once.
3.3.1 The Softmax#
3.3.1.1 Normalizing Each Row#
For a minibatch of examples, the logits form an matrix (Section 3.1.1.4). Softmax normalizes each row independently:
In code, we exponentiate O, sum across columns (axis=1) with keepdims=True so the row sums keep shape (n, 1), and divide via broadcasting:
def softmax(O):
O_exp = d2l.exp(O)
return O_exp / d2l.reduce_sum(O_exp, 1, keepdims=True) # Broadcast
Let us sanity-check softmax on two rows: the cat/chicken/dog logits
from Section 3.1, and a row of three identical
zeros.
O = d2l.tensor([[1.0, 2.2, 0.3], [0.0, 0.0, 0.0]])
Y_hat = softmax(O)
Y_hat, d2l.reduce_sum(Y_hat, 1)(tensor([[0.2076, 0.6893, 0.1031],
[0.3333, 0.3333, 0.3333]]),
tensor([1., 1.]))
3.3.1.2 Overflow#
Why should you never deploy this three-line softmax formula in production? Because in 32-bit floating point (float32), numbers top out near , so overflows to inf as soon as . Feed softmax the logits and evaluates to NaN, even though the true probability distribution is to machine precision.
As we proved in Section 3.1, softmax is invariant to shifting every logit in a row by the same constant. Subtracting the row maximum before exponentiating ensures every exponent is (and the largest is ), making overflow impossible. Every framework's built-in softmax applies this shift internally:
O = d2l.tensor([[1000.0, 0.0, 0.0]])
O_max = O.amax(dim=1, keepdim=True)
softmax(O), softmax(O - O_max), torch.softmax(O, dim=1)(tensor([[nan, 0., 0.]]), tensor([[1., 0., 0.]]), tensor([[1., 0., 0.]]))
For our Fashion-MNIST scratch run below, pixel values lie in and weights stay small, so softmax does not overflow during training; however, shifting alone still leaves very negative logits vulnerable to underflow ( in float32, turning into ). In Section 3.3.5 below, we eliminate both hazards permanently by fusing softmax and the logarithm in log space.
3.3.2 Loss and Accuracy#
3.3.2.1 Two Uses of the Logits#
While gradient descent optimizes the smooth cross-entropy loss, humans judge a classifier by its accuracy—the fraction of examples where the top-scoring class matches the true label :
Both metrics flow from the exact same logit vector (Figure 3.3.1), and tracking both during validation is essential: if a model becomes overconfident on a few mistakes, its validation cross-entropy loss can rise even while its validation accuracy is still climbing.
Training (top) maps logits through softmax to the smooth cross-entropy loss; evaluation (bottom) compares against the label to compute discrete accuracy.
3.3.2.2 The Classifier Class#
We package this dual-metric validation behavior into Classifier(d2l.Module), the base class for every classification model in the book, starting with validation_step returning both 'loss' and 'acc' on each validation minibatch:
class Classifier(d2l.Module):
"""The base class of classification models."""
def validation_step(self, batch):
Y_hat = self(*batch[:-1])
return {'loss': self.loss(Y_hat, batch[-1]),
'acc': self.accuracy(Y_hat, batch[-1])}Next, we attach accuracy(self, Y_hat, Y, averaged=True) to Classifier: it flattens Y_hat to one row of class scores per example, finds the predicted class index via argmax along axis=1, casts it to Y.dtype, and returns either the mean or per-example float32 equality mask preds == Y:
@d2l.add_to_class(Classifier)
def accuracy(self, Y_hat, Y, averaged=True):
"""Compute the fraction of correct predictions."""
Y_hat = d2l.reshape(Y_hat, (-1, Y_hat.shape[-1]))
preds = d2l.astype(d2l.argmax(Y_hat, axis=1), Y.dtype)
compare = d2l.astype(preds == d2l.reshape(Y, (-1,)), d2l.float32)
return d2l.reduce_mean(compare) if averaged else compare
Finally, we install plain minibatch SGD at learning rate self.lr as the default configure_optimizers method on d2l.Module so every classifier inherits a working optimizer out of the box:
@d2l.add_to_class(d2l.Module)
def configure_optimizers(self):
return torch.optim.SGD(self.parameters(), lr=self.lr)3.3.3 The Model and the Loss#
3.3.3.1 The Parameters and Forward Pass#
Flattening each Fashion-MNIST image yields input features for classes, so SoftmaxRegressionScratch allocates (initialized from ) and (initialized to ), totaling parameters. Notice a quick sanity check: near-zero initial weights produce near-zero logits, so the untrained model starts close to a uniform prediction () with initial cross-entropy loss near :
class SoftmaxRegressionScratch(Classifier):
"""Softmax regression implemented from scratch."""
def __init__(self, num_inputs, num_outputs, lr, std=0.01):
super().__init__()
self.save_hyperparameters()
self.W = nn.Parameter(d2l.normal(0, std, (num_inputs, num_outputs)))
self.b = nn.Parameter(d2l.zeros(num_outputs))In forward(self, X), we flatten each image in the minibatch into a row vector of length self.num_inputs () via d2l.reshape(X, (-1, self.num_inputs)) and map the affine logits through softmax:
@d2l.add_to_class(SoftmaxRegressionScratch)
def forward(self, X):
X = d2l.reshape(X, (-1, self.num_inputs)) # One flattened image per row
return softmax(d2l.matmul(X, self.W) + self.b)3.3.3.2 The Cross-Entropy Loss#
Recall from Section 3.1.2 that . Instead of materializing one-hot matrices and taking inner products, we pluck out the true-class probability for every row in one vectorized indexing step:
y = d2l.tensor([0, 2])
y_hat = d2l.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
y_hat[[0, 1], y]tensor([0.1000, 0.5000])
That extracts 0.1 for the first example and 0.5 for the second. Wrapping
this in cross_entropy, we average the negative logarithms across the
minibatch. Notice the one defensive clamp to before taking the
logarithm: it stops an underflowed zero probability from turning into
, capping the per-example loss at , though clamping also
zeroes out the gradient whenever it triggers. Later in this section
(Section 3.3.5), we replace this stopgap with a fused loss computed directly
from logits.
def cross_entropy(y_hat, y):
# Tiny clip to keep log finite when softmax outputs underflow to 0.
p = y_hat[list(range(len(y_hat))), y].clamp(min=1e-12)
return -d2l.reduce_mean(d2l.log(p))
cross_entropy(y_hat, y)tensor(1.4979)
That yields the mean of and ,
or roughly 1.50. Let us attach it as the model's loss method:
@d2l.add_to_class(SoftmaxRegressionScratch)
def loss(self, y_hat, y):
return cross_entropy(y_hat, y)
3.3.4 Training and Evaluation#
3.3.4.1 The Training Run#
Let us train SoftmaxRegressionScratch on Fashion-MNIST for epochs with minibatch size and learning rate :
data = d2l.FashionMNIST(batch_size=256)
model = SoftmaxRegressionScratch(num_inputs=784, num_outputs=10, lr=0.1)
trainer = d2l.Trainer(max_epochs=10)
trainer.fit(model, data)To score a trained model on an entire dataset split whenever we want, we attach an evaluate(self, model, data, train=False) helper to d2l.Trainer that binds self.val_dataloader to either the validation or training loader and runs self.validate():
@d2l.add_to_class(d2l.Trainer)
def evaluate(self, model, data, train=False):
"""Metrics of `model` on the validation data of `data` (on its training
data if `train`), averaged over examples."""
self.train_dataloader = None
self.val_dataloader = (data.train_dataloader() if train
else data.val_dataloader())
self.prepare_model(model)
return self.validate()
Averaged across all 10,000 validation images, these metrics match the final
points recorded in trainer.history['val_loss'][-1] and
trainer.history['val_acc'][-1].
trainer.evaluate(model, data){'loss': 0.500844775390625, 'acc': 0.8284}
Our classifier gets roughly of the validation images right; passing train=True evaluates the exact same weights across all training images:
trainer.evaluate(model, data, train=True){'loss': 0.46587086588541665, 'acc': 0.8420666666666666}
After 10 epochs, validation accuracy settles near (varying by across random seeds) and training accuracy sits near . That tiny generalization gap reflects the restricted capacity of a linear classifier: parameters cannot memorize images (Section 3.5).
3.3.4.2 Misclassified Images#
To see how the model errs, let us pull the first validation minibatch of images and count the mistakes:
X, y = next(iter(data.val_dataloader()))
preds = d2l.astype(d2l.argmax(model(X), axis=1), y.dtype)
wrong = preds != y
print(f'{int(d2l.reduce_sum(d2l.astype(wrong, d2l.int32)))} of {len(y)} wrong')35 of 256 wrong
Let us display the first eight misclassified images, showing the true label
above the model's prediction (true → pred):
labels = [f'{true}\n→ {pred}' for true, pred in zip(
data.text_labels(y[wrong]), data.text_labels(preds[wrong]))]
data.visualize([X[wrong], y[wrong]], labels=labels)3.3.4.3 The Confusion Matrix#
To summarize the error pattern across all validation images, we tally the confusion matrix , where rows index the predicted class and columns index the true class :
(Placing true classes in the columns and predicted classes in the rows makes column-normalized conditional probabilities multiply cleanly as when we study label shift in Section 3.6.) Using one-hot matrices for a minibatch's predicted and true classes, the product accumulates all counts in a single matrix multiplication per minibatch:
def one_hot(y, q):
"""Rows of the q x q identity matrix, one per class index in y."""
return d2l.astype(d2l.reshape(y, (-1, 1)) == d2l.arange(q, dtype=y.dtype),
d2l.float32)
N = d2l.zeros((10, 10))
for X, y in data.val_dataloader():
P = one_hot(d2l.argmax(model(X), axis=1), 10)
N += d2l.matmul(d2l.transpose(P), one_hot(y, 10))
int(d2l.reduce_sum(N))
10000
All 10,000 validation images are accounted for. Because raw counts depend
on class frequency, we normalize each column of by its sum to
obtain , an empirical estimate of the
conditional probability . Each column shows
where examples of true class land, while the diagonal gives per-class
recognition rates. Let us render as a heatmap via
d2l.show_heatmaps.
C = N / d2l.reduce_sum(N, 0, keepdims=True) # Each column sums to 1
names = data.text_labels(range(10))
d2l.show_heatmaps(d2l.reshape(C, (1, 1, 10, 10)), xlabel='true class',
ylabel='predicted class', figsize=(4, 4), cmap='Blues',
xticklabels=names, yticklabels=names)Let us also print the five largest off-diagonal entries to spotlight the most frequent confusions:
mistakes = d2l.numpy(N) * (1 - np.eye(10)) # Zero the diagonal
for k in np.argsort(mistakes, axis=None)[::-1][:5]:
i, j = divmod(int(k), 10)
print(f'{names[j]} taken for {names[i]}: {int(mistakes[i, j])}')shirt taken for pullover: 207
coat taken for pullover: 192
shirt taken for T-shirt: 192
shirt taken for coat: 151
pullover taken for coat: 102
The confusion matrix confirms what our visual inspection in Section 3.2 predicted: trousers, bags, and footwear are recognized of the time or better, whereas the five largest off-diagonal confusions all occur among the four look-alike upper-body tops (T-shirt, pullover, coat, and shirt)—with shirts recognized only about half the time or less because their silhouette sits right in the middle of the other three.
3.3.4.4 The Learned Templates#
Because each logit is an inner product between the flattened image and column of , reshaping each 784-element column back to lets us view the entire classifier as ten visual templates (red = positive weights, blue = negative weights):
W = d2l.numpy(model.W)
templates = W.T.reshape(10, 28, 28) # Column j of W as an image
v = np.abs(templates).max()
d2l.show_images(templates, 2, 5, titles=names, cmap='RdBu_r', vmin=-v, vmax=v);Each template is a recognizable ghostly silhouette of its garment—notice the blue negative channel between the trouser legs that penalizes dresses, and the similar torso shapes of the four tops that differ mainly around the collar and sleeves. Because a linear layer can only take a single fixed global dot product per class, subtle local features like collars or buttons cannot overcome overall silhouette overlap; breaking past requires nonlinear hidden layers (Chapter 4) and spatial convolutions (Chapter 6).
3.3.5 Concise Implementation#
Now let us see how deep learning frameworks simplify softmax regression while permanently curing the overflow and underflow hazards of our naive softmax and clamped cross_entropy.
3.3.5.1 Defining the Model#
In SoftmaxRegression(d2l.Classifier), a flattening step and a single built-in fully connected layer with outputs compute the logits (initialized with weights and zero biases to match our scratch baseline). Crucially, forward returns the raw logits directly, without applying softmax:
class SoftmaxRegression(d2l.Classifier):
"""The softmax regression model."""
def __init__(self, num_outputs, lr):
super().__init__()
self.save_hyperparameters()
self.net = nn.Sequential(nn.Flatten(),
nn.LazyLinear(num_outputs))
def weight_init(self, module):
# The Trainer calls this after the lazy layer has learned its shape
if isinstance(module, nn.Linear):
nn.init.normal_(module.weight, std=0.01)
nn.init.zeros_(module.bias)
def forward(self, X):
return self.net(X)3.3.5.2 A Stable Cross-Entropy Loss#
Why does SoftmaxRegression.forward stop at the logits instead of returning probabilities? Recall the twin floating-point hazards of computing first and second in float32:
- Overflow: overflows to
inffor . Subtracting from every logit fixes overflow because every shifted exponent is . - Underflow: Even after shifting by , any class whose logit sits more than below (such as the second class, label 1 in code, in ) has underflow to exact
0.0in float32. Taking then produces-inf(or, with our scratch1e-12clamp, caps the loss at and zeroes out the gradient, leaving the model unable to learn from a confident blunder).
We avoid both overflow and underflow by never materializing intermediate probabilities at all. Combining the logarithm and the shifted softmax algebraically via the LogSumExp trick turns the division into a subtraction:
Because every shifted exponent is and at least one equals , the sum inside the logarithm lies in , and its logarithm in . Neither overflow nor can occur, and automatic differentiation yields the finite gradient .
Every framework provides this fused log-sum-exp cross-entropy. We install it once on d2l.Classifier.loss so every classifier in the rest of the book inherits it:
@d2l.add_to_class(d2l.Classifier)
def loss(self, Y_hat, Y, averaged=True):
Y_hat = d2l.reshape(Y_hat, (-1, Y_hat.shape[-1]))
Y = d2l.reshape(Y, (-1,))
return F.cross_entropy(
Y_hat, Y, reduction='mean' if averaged else 'none')Testing SoftmaxRegression.loss on the extreme logits O = [[1000.0, 0.0, 0.0], [1000.0, 0.0, 0.0]] with true labels y = [0, 1] confirms that the fused LogSumExp implementation returns the exact per-example losses [0., 1000.] without overflow or underflow:
O = d2l.tensor([[1000.0, 0.0, 0.0], [1000.0, 0.0, 0.0]])
y = d2l.tensor([0, 1])
SoftmaxRegression(num_outputs=3, lr=0.1).loss(O, y, averaged=False)tensor([ -0., 1000.])
(Watch out for one classic pitfall: because Classifier.loss expects raw logits and applies log-softmax internally, accidentally placing a softmax at the end of forward applies softmax twice, trapping the training loss above a positive floor; see Exercise 4 below.)
3.3.5.3 Training#
Training SoftmaxRegression with d2l.Trainer takes four lines and reproduces our validation accuracy with rock-solid numerical stability:
data = d2l.FashionMNIST(batch_size=256)
model = SoftmaxRegression(num_outputs=10, lr=0.1)
trainer = d2l.Trainer(max_epochs=10)
trainer.fit(model, data)3.3.6 Summary#
Implementing softmax regression from scratch introduces the reusable Classifier base class, which pairs smooth cross-entropy optimization during training with discrete accuracy during validation, reaching roughly validation accuracy on Fashion-MNIST in ten epochs. Accumulating one-hot products builds the confusion matrix and reveals that linear errors concentrate among the four upper-body garments whose learned weight templates overlap strongly. Because computing softmax and log separately overflows for large positive logits and underflows to for large negative logits, our concise implementation returns raw logits from forward and evaluates the shifted log-sum-exp cross-entropy , guaranteeing finite values and intact gradients across all logit magnitudes.
3.3.7 Exercises#
-
[code] Cross-entropy from one-hot labels. The
cross_entropyof this section selects the correct-class probability by indexing. Implement an alternative that follows the definition literally, by convertingyto a one-hot matrix and taking row-wise inner products.- Use it as the
lossofSoftmaxRegressionScratchand confirm that training is unchanged. - Time both versions on random probability matrices with rows and columns, and state how the memory that each version allocates grows with .
- Describe a setting in which the inner-product form applies but the indexing form does not.
- Use it as the
-
Large vocabularies. Suppose that softmax regression predicts the next word from a feature vector of dimension . The vocabulary has words, and each minibatch holds examples. List the operations of
forwardandcross_entropywhose cost grows with . Compute the multiply-adds of the matrix product, the float32 memory ofW, and the float32 memory of the matrix of probabilities, and compare each number with the Fashion-MNIST model of this section. -
[code] Templates and class means. The templates are what minibatch SGD made of the pixels it saw.
- Train
SoftmaxRegressionScratchagain withstd=0, so that every weight starts at 0 and every class starts with the same logit. Explain why training works all the same, and compare the accuracy and the templates with those of the text. - Show that after one SGD step from zero weights, column of is proportional to over the first minibatch: the sum of the images of class minus a tenth of the sum of all images.
- Compute the mean image of each class over the training set and compare it with the trained template of that class, by eye and by the correlation of their pixels. Where do they agree, and where does a template depart from the mean? Explain why a template that merely copied the class mean would confuse the tops even more.
- Train
-
[code] Double softmax. The
lossof this section expects logits. Suppose that a model'sforwardmistakenly ends with a softmax. The loss then receives a probability vector in place of the logits and evaluates .- Find the smallest value this loss can take over all probability vectors and labels , as a function of the number of classes . Evaluate it for .
- Use the from-scratch
softmaxdefined earlier in this section, which is not part of thed2lpackage. SubclassSoftmaxRegressionso thatforwardapplies thissoftmaxto the logits. Train it withlr=0.1,d2l.FashionMNIST(batch_size=256), andd2l.Trainer(max_epochs=10). Compare its training loss and validation accuracy with those ofSoftmaxRegression, and relate the final training loss to the value from the previous step.
-
[code] Stable softplus. For two classes with logits , the first term of the loss is , the softplus of .
- Plot and on . Show that the first exceeds the second by at most , at , and explain in one sentence why log-sum-exp is called a smooth maximum.
- Show that .
- In single precision, evaluate the naive expression
log(1 + exp(x)), the rewritten expression, and the rewritten expression withlog1pin place oflog(1 + ...), for . Compare each value with a double-precision reference, and report where each version overflows and where it loses all relative accuracy. - Compute the derivative of the naive expression at by automatic differentiation. Explain why it is accurate although the value of the expression is not, and what this implies for training and for reporting the loss of confidently classified examples.
-
[code] The gradient survives. For the logits with true label 1, the shifted softmax probability of class 1 underflows to in float32, so the clamped scratch loss
cross_entropy(softmax(O - O_max), y)hits its1e-12floor and has zero gradient with respect to the logits. Pass the same logits and label to the fusedlossofSoftmaxRegressionand compute the gradient with respect to the logits by automatic differentiation. Compare it with from Section 3.1, and explain why the fused loss moves the logit of class 1 while the clamped scratch loss does not. -
Number formats. Half-precision formats store a number in 16 bits: FP16 has 5 exponent bits and 10 mantissa bits, BFLOAT16 has 8 and 7, and FP32 has 8 and 23. Determine for each format the largest logit for which does not overflow. Then explain why a network whose logits reach 20 can be trained in BFLOAT16 but not in FP16 unless its softmax is computed in FP32. Finally, consider the shifted sum of (3.3.4) for classes, each term at most 1, accumulated in FP16: what goes wrong once the running sum exceeds 2,048, and what does the 10-bit mantissa have to do with it?