Loss Function
A loss function is a single number measuring how wrong a model's predictions are, which gradient descent minimizes during training.
A loss function translates "how wrong was this prediction" into a single, differentiable number that gradient descentGradient DescentGradient descent is the optimization algorithm that trains models by repeatedly stepping parameters in the opposite direction of the loss function's gradient. can minimize. Mean squared error (MSE) is common for predicting continuous values; cross-entropy loss is standard for classification (including next-token prediction in LLMsLLM (Large Language Model)An LLM is a large transformer trained to predict the next token on massive text corpora, then fine-tuned to follow instructions — the architecture behind GPT, Claude, Gemini, and Llama.), since it penalizes confidently wrong predictions heavily. The choice of loss function directly encodes what the model is actually optimized to do.
How it works
The loss maps a prediction and a target to a scalar, and must be differentiable with respect to the model's outputs so that backpropagationBackpropagationBackpropagation is the algorithm that computes the gradient of a neural network's loss with respect to every parameter, by applying the chain rule backward through the network. has something to differentiate.
- MSE:
mean((y_pred - y)**2)— penalizes large errors quadratically, so it is sensitive to outliers.L1/Huber are the robust alternatives. - Cross-entropy:
-log(p_correct). It is unbounded above, so a prediction that is both confident and wrong contributes an enormous gradient, while a confident correct prediction contributes almost none.
In practice the model emits raw logits and the loss applies softmax or sigmoid internally, because the fused form is numerically stable. The reported loss is averaged over the batch, which is why it is comparable across batch sizes.
When it breaks
- Loss and the metric you care about diverge. Cross-entropy can improve while accuracy, F1, or user-visible quality does not — the loss is a differentiable proxy, not the objective.
- Double softmax. Passing already-normalized probabilities into a
loss that expects logits (PyTorch's
CrossEntropyLoss,BCEWithLogitsLoss) silently flattens gradients. - Class imbalance. With 99% negatives, the minimum-loss solution is to predict the majority class always. Class weights or focal loss are the usual corrections.
- Numerical blowups. Hand-rolled
log(p)hits-infwhenpis exactly0; use the library's fused logit version or add an epsilon.
See also: Gradient DescentGradient DescentGradient descent is the optimization algorithm that trains models by repeatedly stepping parameters in the opposite direction of the loss function's gradient., OverfittingOverfittingOverfitting is when a model fits its training data (including noise) so closely that it fails to generalize to new, unseen data.
Learn more: ML Fundamentals · Wikipedia: Loss function
Mentioned in
Lessons where this comes up in context.
- AI Safety & AlignmentWhether a model's own objectives match what we actually want, independent of any attacker — specification gaming, outer vs. inner alignment, why RLHF isn't a complete answer, and scalable oversight
- Computer VisionConvolutions, pooling, CNNs, transfer learning
- Generative ModelsGANs, VAEs, and diffusion models — how AI generates new images, audio, and video, as opposed to classifying or understanding existing content
- LLMsTokenization, embeddings, pretraining vs fine-tuning, RLHF basics
- ML FundamentalsSupervised/unsupervised learning, loss functions, gradient descent
- Probability & Statistics FoundationsDistributions, Bayes' theorem, and maximum likelihood estimation — the math that loss functions and uncertainty in ML are actually built on
- Reinforcement LearningMDPs, reward, policy and value functions, Q-learning — the third major ML paradigm, and the actual mechanism behind RLHF
- Tooling & The Dev StackLanguages, frameworks, and where they fit — what you'd actually touch to build and ship a model
Universal Approximation Theorem
The universal approximation theorem proves that a feedforward network with even one hidden layer can approximate any continuous function, given enough neurons.
Overfitting
Overfitting is when a model fits its training data (including noise) so closely that it fails to generalize to new, unseen data.