Cheat sheets
Loss functions
Which loss to train with for each task, and what each one encourages.
A loss is what the optimizer minimizes; a metric is what people judge. Pick the metric first, then a loss that pushes in the same direction.
| Task | Loss | Formula (one example) | Encourages |
|---|---|---|---|
| Regression | MSE | close predictions; punishes big misses | |
| Robust regression | MAE / Huber | / hybrid | less outlier influence |
| Binary classification | binary cross-entropy | high probability on the true label | |
| Multiclass | categorical cross-entropy | high probability on the true class | |
| Language modeling | token cross-entropy | predicting the next token | |
| Margin classification | hinge | a margin between classes (SVM) | |
| Metric learning | contrastive / triplet / InfoNCE | pull positives together, push negatives apart | similar items close in embedding space |
| Reconstruction | MSE / cross-entropy on inputs | autoencoders | |
| Diffusion | noise-prediction MSE | denoising |
Implementation tips. Pass logits, not probabilities, to BCEWithLogitsLoss and CrossEntropyLoss (numerically stable). Add regularization terms () to the loss, or use weight decay in the optimizer (AdamW).
Quick numbers. Cross-entropy for : .
Lessons: Logistic regression · Forward pass · Tokenization and pretraining