Loss and Gradient
A model is a function or with adjustable params .
Now when we say a model "learns". Learning refers to choosing good values of . But "good" needs to be a number before anything can be optimised.
Loss is exactly this number which takes the prediction and the true answer and returns a non-negative score of how wrong the predicted value is ( = minimum, which means the prediction is perfect).
Learning becomes :
Everything in machine learning for example, Gradient descent, backprop, training loop is for minimizing the loss.
To describe the loss let's take the example of loss for a single entry from our dataset. Formally, a loss function is a map :
Or we can say that for a set of prediction and actual value our map becomes :
Also to represent the loss for the whole dataset we will use (this is known as Empirical Risk)
Loss Types
Now there are several ways to represent loss and every type has it's own pros and cons.

Squared Loss
In this type the penalty grows quadratically with miss distance.
Absolute loss
In this type the penalty grows linearly not quadratically. One of the pros of using this loss is that the outliers in the data pull less hardly when penalty is applied.
0-1 loss
In this type it returns 1 when wrong, 0 when correct (it counts errors).
We can clearly see the problem: This loss is piecewise constant so its gradient is zero wherever it's defined and undefined at the jumps. Gradient descent gets no signal from it because there's no slope pointing toward "less wrong." This is exactly why we need smooth surrogate losses like cross-entropy which is what the next section introduces.
Cross Entropy / Negative Log Likelihood

The model outputs a probability distribution (via softmax) :
Here as approaches 0, our loss approaches .
Where Do These Losses Come From?
Almost every standard loss is the same object in disguise: the negative log-likelihood of the data under an assumed noise model.
The recipe has three steps:
- Assume a probability model for the label given the input: .
- Maximize likelihood pick making the observed data most probable:
- Take , the logarithm is monotonic (so it doesn't move the maximizer) and it turns the product into a sum and the max into a min:
Compare this to : the per example loss is the negative log likelihood, .
Gaussian noise gives squared loss. If you assume the label is the model's prediction plus bell-curve noise, minimizing squared error is exactly maximum likelihood. This is why least-squares is everywhere and that's why it's outlier-sensitive. The Gaussian assigns tiny probability to large deviations so the fit distorts to avoid them.
Derivation: Gaussian noise ⟹ squared loss
Assume with , so
Take the negative log of one term:
The additive constant doesn't affect the minimizer, and the factor is a positive constant that only rescales now drop both, and you're minimizing . Least squares = MLE under Gaussian noise.
(Swap the Gaussian for a Laplace distribution and the same computation yields absolute loss leading to heavier tails, which is why absolute loss tolerates outliers.)
Categorical labels give cross-entropy. If you assume the label is drawn from a categorical distribution whose probabilities are the model's softmax outputs, the negative log-likelihood is precisely which is the cross-entropy from the previous section.
Derivation: categorical labels ⟹ cross-entropy
For a -class label, assume is drawn from a categorical distribution with , where . Using the one-hot encoding of the true label, the probability of the observed class is
The negative log-likelihood of one example is therefore
which is exactly cross-entropy. So the softmax + cross-entropy pairing you see everywhere in classification isn't two independent choices, it's one choice (a categorical likelihood) written in two pieces.
Gradients

We now have a loss and a goal which is to minimize it. To "minimize" is kind of unclear. To actually move the weights toward a smaller loss, we need to know, at our current , which way is downhill. That direction is what the gradient gives us.
Notation from here on. We are moving into vectors and matrices. Bold lowercase letters () are vectors; capitals () are matrices; plain lowercase () are scalars. A subscript picks out an entry: is the -th component of .
One dimension: the derivative
For a function of a single variable , the derivative is the local slope:
It answers: if I nudge a little, how fast does change? It carries two pieces of info :
- its sign tells you the direction of increase (positive slope means increasing increases )
- its magnitude tells you how sensitive is to that nudge.
Many dimensions: partial derivatives
Now let be the loss as a function of all weights . There is no single "slope" anymore, because from any point you can move in infinitely many directions. But you can still ask the one-dimensional question one coordinate at a time:
In words: hold every weight fixed except , nudge only , measure the response. That is a partial derivative which one number per coordinate.
The mechanic in practice is to treat every other variable as a constant. For example, with :
Stacking them: the gradient
The gradient collects all partial derivatives into a single vector:
Why this particular vector matters
The gradient compresses all directional information into one object. Take a small step from and ask how changes. The first-order Taylor expansion says:
So the change in under any direction of movement is just an inner product with the gradient. Now use the geometric form of the inner product, , and sweep over all unit directions :
- increases fastest when that is, in the direction of itself. So the gradient points in the direction of steepest ascent, and is that maximal rate of increase.
- decreases fastest when the direction . This is steepest descent, and it is exactly the direction we will step in next.
- Directions with (perpendicular to the gradient) leave unchanged to first order. In other words, the gradient is orthogonal to the level sets (the contour lines of constant loss). That last fact is worth holding onto — every contour picture for the rest of this post is readable because the gradient always crosses the contours at right angles.
One consequence: at a minimum, no direction decreases , which forces
"Minimizing the loss" concretely means "finding where the gradient is zero."
Two matrix-calculus identities we'll reuse (with proofs)
These are the vector analogues of and . Everything reduces to the coordinate-wise partials above plus careful indexing.
Identity 1: .
Write it out: . Take the partial with respect to — every term dies except :
Identity 2: for symmetric .
Expand: . Take ; the variable appears when and when :
So in general , and when is symmetric () this collapses to . (We'll only ever apply this to , which is always symmetric — so we're safe.)
Gradient Descent
The gradient hands us a downhill direction at every point. Gradient descent is nothing more than: stand where you are, look at , take a step that way, repeat.
is the locally steepest uphill direction; the minus sign flips it downhill; (the learning rate) scales how far we move; and we repeat until , i.e. until no direction goes downhill anymore.
The learning rate is delicate

That single number controls everything, and picking it badly breaks training. On the same loss surface, four regimes:
- Too small. The steps are tiny; the iterates crawl toward the minimum and waste thousands of steps getting there.
- Well-chosen. The iterates glide smoothly down into the minimum in a handful of steps.
- Too big. Each step overshoots the bottom and lands on the far wall; the path zig-zags across the valley, making slow progress at best.
- Way too big. The overshoot grows every step. The iterates spiral outward and the loss diverges to infinity.
Personal To Study Note (Not part of the main article) :warning: 🚨 AI GENERATED CONTENT (NOT VERIFIED) 🚨 :warning:
Why Speed Varies: Conditioning
Here is the question from the last section, sharpened: why does the same algorithm need ten steps on one problem and ten thousand on another? The answer is the shape of the loss surface, and for least-squares we can work it out exactly.
Least-squares is an exact quadratic bowl
Take linear regression with squared loss. Writing the predictions as (the design matrix times the weights):
Expand and differentiate using the two identities from earlier (this is where the we carried since the squared-loss definition it cancels the 2 from the derivative):
Differentiate once more to get the Hessian which is the matrix of second partial derivatives, i.e. the derivative of the gradient:
Notice what did not happen: has no in it. The Hessian is constant. That means is exactly a quadratic function — a -dimensional paraboloid, a bowl — with no approximation anywhere. (For a neural network the loss isn't globally quadratic, but near a minimum this same analysis applies via a second-order Taylor expansion. Mastering the linear case is how you understand the general one.)
The minimizer, and the gradient rewritten around it
Setting gives the Normal Equation:
Now a small trick that makes everything downstream trivial. Since , substitute it back into the gradient:
The gradient is a linear function of the error . Hold onto this line — it's the engine of the whole argument.
Eigenvalues are the curvatures of the bowl
is symmetric and positive (semi-)definite, so by the spectral theorem it has an orthonormal eigendecomposition:
where the columns of are orthonormal eigenvectors. What does an eigenvalue mean here? Step a distance away from the minimum along eigendirection and measure the loss (exact, since is quadratic):
So along the loss is a 1-D parabola with curvature . Large = steep, tight valley wall; small = nearly flat floor. The level sets are ellipsoids whose axis along has length proportional to . If and , the ellipse is longer in one direction than the other — a long, narrow ravine.
The condition number measures exactly this lopsidedness — the ratio of steepest to shallowest curvature:
is a perfectly round bowl; is a pathological ravine.
Gradient descent decouples, one eigendirection at a time
Now run gradient descent on this bowl and watch the error evolve. Start from the update rule, substitute the error-form of the gradient, and define the error :
The error just gets multiplied by the fixed matrix every step. Change basis to the eigenvectors — let be the component of the error along eigendirection . Because is diagonal, the directions stop interacting:
This is the whole story in one line. Gradient descent on a quadratic decouples into independent 1-D problems, one per eigendirection, each shrinking geometrically at its own rate . There is no cross-talk between directions.
The divergence cliff, explained
Direction converges if and only if , which rearranges to . This must hold for every direction at once, and the binding constraint is the largest eigenvalue:
There is the cliff from the previous section. If , the component along the steepest direction has , so it fails to shrink — it oscillates with non-decreasing amplitude and the iterates bounce up the ravine walls, higher each time. Divergence is caused entirely by the steepest direction. The "way too big" regime wasn't mysterious; it was crossing .
The speed limit
Here's the tension. You'd love to crank up to make the slowest direction (rate ) converge faster — but the steep direction caps you at . The best you can do is balance them. Minimizing the worst-case contraction rate over all directions gives the optimal step size and rate:
Where η* and the (κ−1)/(κ+1) rate come from
The worst-case contraction over all directions is (the max is always attained at an extreme eigenvalue). To minimize this max, we balance the two endpoints so they have equal magnitude with opposite signs:
Substituting back:
iterations. The number of steps scales linearly with the condition number. means on the order of a million iterations where a round bowl () would take a handful. That is the precise, quantitative reason "some problems train in ten steps and others in ten thousand."
Why O(κ) iterations
To drive the error below we need , i.e. . For large , write and use for small :
Now the payoff. Where does a large actually come from? Look at the entries of :
The diagonal entry is the mean squared magnitude of feature . Feature scales sit directly on the Hessian's diagonal. Take two uncorrelated features — house size (, so ) and bedroom count (, so ). With no correlation, is diagonal, its eigenvalues are those diagonal entries, and
The ravine — and the resulting ten-thousand-step slog — comes entirely from the two features being measured in different units.
Standardization fixes exactly this. After rescaling every feature to mean 0 and variance 1, each diagonal entry becomes , and becomes the feature correlation matrix. If the features are roughly uncorrelated that's approximately the identity, whose eigenvalues are all 1 — so , a round bowl, and gradient descent converges almost immediately. This is the whole reason normalization speeds up training: it collapses the condition number. Not folklore — a theorem about the Hessian's eigenvalues.
Honest caveat. Standardization equalizes the diagonal but does not remove correlations (the off-diagonal terms). Two highly correlated features still produce a large : for correlation , the correlation matrix has eigenvalues and , so as . Fully fixing that needs whitening (rotate into the eigenbasis and rescale), which is usually too expensive to bother with. Standardization is the cheap fix that kills the scale-induced part of the ill-conditioning — in practice, usually the dominant part.