Loss Functions › Loss Function Selection for NLP Tasks
Language AI HandbookAll chapters Loss Functions › Loss Function Selection for NLP TasksOne section · Sections in this chapter12 / 17 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Choosing the right loss function is about matching the loss to the structure of the task. Here is a practical guide for common NLP scenarios.
Text classification (spam detection, sentiment, topic): Use categorical cross-entropy for single-label, binary cross-entropy per class for multi-label. Label smoothing (0.1) is a low-cost improvement for calibration.
Named entity recognition (NER): Token-level classification. Use categorical cross-entropy with class weights or focal loss if entity classes are rare compared to non-entity tokens. Most production NER systems deal with severe label imbalance because most tokens are not entities.
Language modeling (next-token prediction): Categorical cross-entropy on the vocabulary distribution. The large vocabulary () requires efficient computation. Label smoothing is sometimes applied at the vocabulary level.
Sequence-to-sequence tasks (translation, summarization): Cross-entropy on each output token, summed or averaged across the sequence. Label smoothing is standard.
Sentence similarity and semantic search: Triplet loss or InfoNCE. SimCSE and similar approaches use a form of noise-contrastive estimation that generalizes contrastive loss to multiple in-batch negatives.
Knowledge distillation: KL divergence between student and teacher distributions, often with temperature scaling to soften teacher outputs.
Regression tasks (predicting scores, ranking): MSE for clean data, Huber loss when outliers are present.
| Task | Recommended Loss | Notes |
|---|---|---|
| Single-label classification | Categorical cross-entropy | Add label smoothing for calibration |
| Multi-label classification | Binary cross-entropy | Per-class sigmoid outputs |
| Class imbalance | Focal loss | gamma=2, alpha=inverse frequency |
| Sequence modeling | Cross-entropy | Label smoothing standard |
| Similarity learning | Triplet or InfoNCE | Hard mining critical for triplet |
| Calibration | Cross-entropy + temperature | Tune T post-training |
| Regression | MSE or Huber | Huber when outliers present |
| Information retrieval | InfoNCE or pairwise ranking | In-batch negatives scale well |
| Knowledge distillation | KL divergence | Apply temperature to teacher logits |