Braj Kishore
JourneyVaultML FoundationsAI PM GuideAgenticNewsWork With MeMentorshipPulseNow
Say hi

Hiring · Building · Investing

Have a system — or a team —that needs to scale?

info@avyxon.ai

Usually replies within a day · track record here

JourneyVaultML FoundationsAI PM GuideAgenticNewsWork With MeMentorshipPulseNow
LinkedInXYouTubeSubstackInstagramThreadsFacebookDiscordGitHubTopmate
© 2026 Braj Kishore · Bengaluru, INThink Big · Start Small · Scale Fast
ML Foundations
04Track 2 · The training loop

Measuring wrongness

Loss functions turn 'that answer was bad' into a number with a gradient — and the one you pick decides what the model considers a mistake.

40 min1 interactive4 sources

A model predicts £310,000 for a house that sold for £400,000. How wrong is that? £90,000? 22.5%? 8.1 billion squared pounds? Each answer is a different loss function, and each one trains a measurably different model.

The intuition

The loss function is the exam marking scheme. Change how you award marks and students change how they study. Square the penalty and the model becomes terrified of large errors, at the cost of tolerating many small ones — which is exactly what happens when one outlier drags a regression line off course.

Unlearn this

That the loss is the metric you care about. It almost never is. Loss must be differentiable so gradient descent can work; your business metric usually isn't. You optimise cross-entropy and you ship on recall-at-fixed-precision, and holding both in mind is the job.

01Loss, cost, objective — and why it must be differentiable

Loss is the error on one example. Cost is the average over a batch or the whole dataset. Objective is whatever you're actually minimising, which is cost plus any regularisation terms. The words get used loosely; the distinction matters when reading papers.

The binding constraint is differentiability. Gradient descent needs a slope at every point to know which way to move. Accuracy has no usable slope — nudge a weight and accuracy either doesn't change at all or jumps discontinuously when a prediction crosses the threshold. That's why you never train on accuracy, and why every practical loss is a smooth surrogate for the thing you really want.

The point

Loss ≠ metric. Loss is what the optimiser can act on; the metric is what the business cares about. If they point in different directions, you'll ship a model with a beautiful loss curve and a bad product.

Neural Networks Part 2: Setting up the Data and the LossStanford CS231n

02Regression: MSE, MAE and the outlier question

Mean squared error squares the residual, so an error of 10 is a hundred times worse than an error of 1. That makes it exquisitely sensitive to outliers — a single mislabelled sale price will visibly tilt your fit. Its gradient is proportional to the error, which is convenient: big mistakes produce big corrections.

Mean absolute error penalises linearly and is therefore robust: outliers get no special treatment. The cost is a constant-magnitude gradient regardless of how wrong you are, which converges less smoothly near the optimum and needs a decaying learning rate.

There's a statistical point worth knowing because it's a favourite follow-up: minimising MSE fits the conditional mean of the target; minimising MAE fits the conditional median. That's not a technicality — it's why an MAE-trained delivery-time model gives you a typical delivery and an MSE-trained one gives you an average dragged up by the disasters.

Huber loss is the pragmatic compromise: quadratic for small residuals, linear beyond a threshold δ. Smooth gradients near the optimum, bounded influence from outliers. It's the default worth reaching for when your target has a heavy tail — prices, durations, transaction amounts.

MSE = (1/n) Σ (yᵢ − ŷᵢ)²

Fits the conditional mean. Outlier-sensitive; gradient scales with the error.

MAE = (1/n) Σ |yᵢ − ŷᵢ|

Fits the conditional median. Robust; constant-magnitude gradient.

Huber = ½e² if |e| ≤ δ, else δ(|e| − ½δ)

Quadratic near zero, linear in the tails. The practical default for heavy-tailed targets.

Descending into ML: Training and LossGoogle ML Crash Course

Try it

What counts as a mistake?

Drag the outlier and watch MSE chase it while MAE ignores it. Then switch to classification for the cross-entropy argument.

03Classification: cross-entropy, and why not MSE

Cross-entropy measures the surprise of the true label under your predicted distribution: −Σ y log ŷ. For binary classification with the true label 1 and a prediction of 0.9 the loss is 0.105; predict 0.1 and it's 2.303; predict 0.01 and it's 4.605. Confident and wrong is punished savagely, and that asymmetry is what stops a model bluffing.

Why not MSE on the class probabilities? Two reasons, and interviewers want both. First, information-theoretic: cross-entropy is the negative log-likelihood of the data under the model, so minimising it is maximum-likelihood estimation — the principled choice for a probabilistic output. Second, and more practically, optimisation: pair sigmoid or softmax with MSE and the gradient carries an extra σ'(z) factor that vanishes exactly when the model is confidently wrong. The model gets almost no signal precisely when it most needs correcting.

Pair them with cross-entropy instead and that factor cancels completely. The gradient of the loss with respect to the pre-activation logits reduces to (ŷ − y) — the raw error. Clean, well-scaled, no saturation. This cancellation is one of the most elegant results in the basics, and being able to state it is a strong signal in an interview.

H(y, ŷ) = −Σ yᵢ log ŷᵢ

Cross-entropy: the surprise of the truth under your predicted distribution.

∂L/∂z = ŷ − y

With softmax + cross-entropy the sigmoid derivative cancels and the gradient is just the error. This is why the pair is standard.

Why logits matter: the numerically stable form fuses softmax into the loss.
import torch, torch.nn as nn

logits = model(x)                 # raw scores — do NOT apply softmax yourself
loss = nn.CrossEntropyLoss()(logits, targets)

# CrossEntropyLoss = LogSoftmax + NLLLoss, fused. Applying softmax first and
# then taking the log separately overflows for large logits and silently
# degrades gradients. Same story with BCEWithLogitsLoss vs sigmoid + BCELoss.
CrossEntropyLoss — why it takes logitsPyTorch

04Class imbalance: fix the data or the threshold before the loss

With a 1-in-1000 positive rate, a model that always says 'negative' achieves 99.9% accuracy and zero business value. The instinct is to reach for a weighted loss — multiply the minority class's contribution by the inverse of its frequency, or use focal loss, which down-weights well-classified examples so training concentrates on the hard ones.

Those work, but reach for them third. First check whether the metric is wrong: optimising average precision instead of accuracy often solves the whole problem without touching the loss. Second, move the decision threshold, which is free, reversible and doesn't require retraining. Only then start re-weighting, because a re-weighted model produces miscalibrated probabilities, and if anything downstream consumes those probabilities you've moved the problem rather than solved it.

The trap

Random oversampling of the minority class before splitting duplicates rows across train and validation — the same example appears on both sides and your metrics become fiction. Resample inside the training fold only.

Focal Loss for Dense Object DetectionLin et al., ICCV · 2017
The vocabulary, defined once
Loss vs cost
Loss is per-example error; cost is the average over the batch or dataset, plus regularisation.
MSE / MAE / Huber
Squared (fits the mean, outlier-sensitive), absolute (fits the median, robust), and the hybrid that gets both.
Cross-entropy
Negative log-likelihood of the true label under the predicted distribution. The standard classification loss.
Logits
Raw pre-softmax scores. Losses take logits directly for numerical stability — never softmax first.
Focal loss
Cross-entropy scaled to down-weight easy examples, concentrating training on hard ones. Built for extreme imbalance in object detection.
Surrogate loss
A differentiable stand-in for the metric you actually care about. Every training loss is one.

The lab

Everything above, with the dials exposed. Break it deliberately — the failure modes are where the understanding is.

Try it

What counts as a mistake?

Drag the outlier and watch MSE chase it while MAE ignores it. Then switch to classification for the cross-entropy argument.

What they actually ask

Measuring wrongness — the interview questions

QYou're predicting delivery times. MSE or MAE?Answer it out loud first, then open this

Depends what 'good' means. MSE fits the conditional mean and hates large misses, so it's right if a 40-minute miss is disproportionately worse than four 10-minute misses. MAE fits the median and gives a typical delivery time, which is usually what a customer-facing ETA wants. In practice I'd use Huber, or train quantile losses to give a range rather than a point — an ETA with a p90 is a better product than an ETA with an average.

What they're listening for
Mentioning quantile regression for an ETA problem is the answer that gets remembered.

QYour classes are 99.5% negative. Walk me through your approach.Answer it out loud first, then open this

First change the metric — accuracy is meaningless here, so precision-recall AUC and recall at a fixed precision. Then set the threshold from the cost of each error type rather than leaving it at 0.5. Then consider class weights or focal loss, knowing they'll distort calibration. Resampling only inside the training fold. And I'd hold out by time, since imbalanced problems like fraud are usually non-stationary too.

QWhat's the gradient of softmax + cross-entropy with respect to the logits?Answer it out loud first, then open this

ŷ − y — the predicted distribution minus the one-hot truth. The softmax Jacobian and the log cancel, which is exactly why the pair is used together and why frameworks fuse them into one op for stability.

Before you move on

Recall beats re-reading, every time. Answer before you flip.

Measuring wrongness · self-test1 / 3

Why can't you train directly on accuracy?

Go to the primary sources

Where each claim above comes from. Open them alongside the lesson rather than after it — the papers are shorter than you think, and the figures usually carry the whole argument.

Paper
  • Focal Loss for Dense Object Detection(2017)Lin et al., ICCVWhere focal loss comes from, and a clear statement of why extreme foreground/background imbalance breaks ordinary cross-entropy.
Docs
  • Descending into ML: Training and LossGoogle ML Crash CourseThe clearest short treatment of squared loss, with an interactive widget for watching outliers drag the line.
  • CrossEntropyLoss — why it takes logitsPyTorchThe primary source for the fused LogSoftmax + NLLLoss behaviour, and the note about numerical stability that catches everyone once.
  • Neural Networks Part 2: Setting up the Data and the LossStanford CS231nLoss functions, regularisation and the relationship between them, written for people who will implement it.

External links open in a new tab. Every URL was reachable when this page was written; links rot, so treat the list as a map rather than a guarantee.

Got it? Tick it off — progress saves on this device.

← PreviousOne neuronNext →Gradient descent
What counts as a mistake?
Task
£200k£400k£600k£800kdrag mefloor area →
With the outlier near the trend, all three losses agree — which is the normal case, and why the choice looks unimportant until it isn't. Drag the outlier to £850k and watch the red MSE line chase it while the green MAE line stays put.

A loss function is the marking scheme. Change how you award penalties and the model changes what it optimises for — which is why the choice is a modelling decision, not a default.

What counts as a mistake?
Task
£200k£400k£600k£800kdrag mefloor area →
With the outlier near the trend, all three losses agree — which is the normal case, and why the choice looks unimportant until it isn't. Drag the outlier to £850k and watch the red MSE line chase it while the green MAE line stays put.

A loss function is the marking scheme. Change how you award penalties and the model changes what it optimises for — which is why the choice is a modelling decision, not a default.