liveBook · Manning

Cross entropy loss

As explained in Learn Generative AI with PyTorch

A loss measure that compares predicted token distributions with the target next tokens for multiclass sequence prediction.

Cross-entropy loss measures the difference between predicted class probabilities and the true labels. It is commonly used when a model chooses among multiple categories, including clothing classes or the next token in a sequence. section 2.2.1 section 14.1.3

For multicategory classification, PyTorch’s nn.CrossEntropyLoss() accepts raw output logits: it combines LogSoftmax and NLLLoss internally, so applying softmax before the loss is unnecessary. Softmax converts the class scores into values that sum to one; binary classification instead uses a sigmoid-style output. section 2.4.2

Training a ten-class clothing classifier

A dense network produces ten logits for ten clothing categories. The training loop computes loss = loss_fn(preds, labels), clears gradients, backpropagates the loss, and updates weights with Adam. Validation repeats the loss calculation without updating the model. The resulting class predictions can be compared with labels to calculate accuracy.

Predicting the next music token

A music Transformer compares each predicted token distribution with the shifted target sequence. Padding can be excluded with ignore_index=389, while gradient clipping limits the gradient norm during optimization. section 14.1.3 section 14.4.1

How Learn Generative AI with PyTorch covers it

How deep it goes
Explains the loss concept, logits interface, internal LogSoftmax and NLLLoss combination, padding exclusion, and training-loop placement.
Examples
Uses ten-class clothing classification and next-token music generation as worked applications.
What it assumes
Assumes labeled examples, model outputs, target tensors, backpropagation, and an optimizer such as Adam.
What you can do after
Apply it via PyTorch to train classifiers and Transformers, including padded token sequences with an ignored target index.
How it connects
Connects multicategory classification with softmax, logits, NLLLoss, Adam optimization, sequence modeling, padding, and gradient clipping.

Also explained in

Compare how 19 books explain cross entropy loss →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Generative AI with PyTorch. The section links point to the parts of the book it draws on.