Classification needs a different loss from regression. A classifier produces C scores, one per class, while its target is a single class index y in {0, …, C − 1}. Subtracting that index from a score vector does not give a useful error. Cross-entropy instead judges the prediction by the probability assigned to the correct class. section 2.3.2
The calculation has two parts. Softmax turns the C scores into probabilities that sum to 1; cross-entropy uses the probability of class y to determine the loss. Getting the largest score on the right class is not the whole goal: a tiny lead over another class is less convincing than a prediction that assigns the correct class a probability of 0.9. In PyTorch, `nn.CrossEntropyLoss()` combines the classification-loss calculation, so a training loop can pass it the model’s scores and integer labels. section 2.3.2
Figure 2.7 There are two different distributions: the real distribution on the left and our prediction on the right. To learn, we need a loss function to tell us precisely how different these distributions are. Cross-entropy solves that problem. In most cases, our label defines reality as being 100% for one class and 0% for all the others.
The figure compares the predicted distribution with a target concentrated entirely on the correct class. It shows what the loss must distinguish: not just which class wins, but how the predicted probability is distributed. section 2.3.2
One loss across many time steps
A character-level autoregressive model predicts a class at every time step. Its outputs have shape `(B, T, V)` and its labels have shape `(B, T)`, where V is the vocabulary size. For each t, `nn.CrossEntropyLoss()(x[:, t, :], y[:, t])` receives the familiar `(B, V)` scores and `(B)` labels. Add those per-step losses to return one training loss. The same classification signal is used between predicted and target output sequences in a sequence-to-sequence model. section 7.5.1 section 11.3
def CrossEntLossTime(x, y):
"""
x: output with shape (B, T, V)
y: labels with shape (B, T)
"""
cel = nn.CrossEntropyLoss()
T = x.size(1)
loss = 0
for t in range(T): #1
loss += cel(x[:,t,:], y[:,t]) #2
return loss
The `CrossEntLossTime` listing shows the time-step loop, the score and label slices, and the sum returned to the training loop. section 7.5.1
For a real-versus-fake discriminator, the classification problem is binary. The GAN implementation uses `nn.BCEWithLogitsLoss()` rather than `nn.CrossEntropyLoss()`: the discriminator targets real for real images and fake for generated images, while the generator targets real for its generated images. These are separate losses because the two networks are updated separately. For ordinary regression, use a regression loss such as MSE or L1 instead. section 9.1.1 section 9.1.3 section 2.7


















