Skip to content
ML to LLMs
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.

TaskLossFormula (one example)Encourages
RegressionMSE(y−y^)2(y - \hat{y})^2close predictions; punishes big misses
Robust regressionMAE / Huber∣y−y^∣\lvert y - \hat{y}\rvert / hybridless outlier influence
Binary classificationbinary cross-entropy−[yln⁡p+(1−y)ln⁡(1−p)]-[y\ln p + (1-y)\ln(1-p)]high probability on the true label
Multiclasscategorical cross-entropy−ln⁡ptrue-\ln p_{\text{true}}high probability on the true class
Language modelingtoken cross-entropy−ln⁡P(tk∣t<k)-\ln P(t_k \mid t_{<k})predicting the next token
Margin classificationhingemax⁡(0,1−yf(x))\max(0, 1 - y f(x))a margin between classes (SVM)
Metric learningcontrastive / triplet / InfoNCEpull positives together, push negatives apartsimilar items close in embedding space
ReconstructionMSE / cross-entropy on inputs∥x−x^∥2\lVert x - \hat{x}\rVert^2autoencoders
Diffusionnoise-prediction MSE∥ϵ−ϵθ∥2\lVert \epsilon - \epsilon_\theta\rVert^2denoising

Implementation tips. Pass logits, not probabilities, to BCEWithLogitsLoss and CrossEntropyLoss (numerically stable). Add regularization terms (λ∥w∥2\lambda\lVert w\rVert^2) to the loss, or use weight decay in the optimizer (AdamW).

Quick numbers. Cross-entropy for ptrue=0.9,0.5,0.1,0.01p_{\text{true}} = 0.9, 0.5, 0.1, 0.01: 0.105,0.693,2.303,4.6050.105, 0.693, 2.303, 4.605.

Lessons: Logistic regression · Forward pass · Tokenization and pretraining