Loss and Gradients


< all posts

Published : 2026-07-09

Loss and Gradient

A model is a function fw:RdRf_w : \mathbb R^d \to \mathbb R or fw:RdRKf_w : \mathbb R^d \to \mathbb R^K with adjustable params ww.

Now when we say a model "learns". Learning refers to choosing good values of ww. 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 (00 = minimum, which means the prediction is perfect).

Learning becomes :

w=argminw L(w)w^* = \underset{w}{\arg\min} \space \mathcal{L}(w)

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 :

:Y×YR0\ell : \mathcal{Y} \times \mathcal{Y} \to \mathbb{R}_{\ge 0}

Or we can say that for a set of prediction and actual value (y^,y)(\hat{y}, y) our map becomes :

(y^,y)(y^,y)(\hat{y}, y) \mapsto \ell(\hat{y}, y)

Also to represent the loss for the whole dataset we will use (this is known as Empirical Risk)

L(w)=1ni=1n(y^i,yi)\mathcal{L}(w) = \frac{1}{n}\sum_{i=1}^{n} \ell\bigl(\hat{y}_i, y_i\bigr)

Loss Types

Now there are several ways to represent loss and every type has it's own pros and cons.

Comparison of loss functions

Squared Loss

(y^,y)=12(y^y)2\ell(\hat{y}, y) = \frac{1}{2} (\hat{y} - y)^2

In this type the penalty grows quadratically with miss distance.

Absolute loss

(y^,y)= y^y \ell(\hat{y}, y) = | \space \hat{y} - y \space |

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

(y^,y)=1[y^y]\ell(\hat{y}, y) = \mathbb{1}[\hat{y} \ne y]

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

Comparison of loss functions

The model outputs a probability distribution p^ΔK1\hat{p} \in \Delta^{K - 1} (via softmax) :

(y^,y)=logp^y\ell(\hat{y}, y) = - \log{\hat{p}_y}

Here as p^y\hat{p}_y approaches 0, our loss \ell approaches \infty.

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:

  1. Assume a probability model for the label given the input: p(yx;w)p(y \mid x; w).
  2. Maximize likelihood pick ww making the observed data most probable: maxw  i=1np(yixi;w)\max_{w}\; \prod_{i=1}^{n} p(y_i \mid x_i; w)
  3. Take log-\log, 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: wMLE=argminw  i=1nlogp(yixi;w)w_{\text{MLE}} = \underset{w}{\arg\min}\; \sum_{i=1}^{n} -\log p(y_i \mid x_i; w)

Compare this to L(w)=1ni(y^i,yi)\mathcal{L}(w) = \frac{1}{n}\sum_{i} \ell(\hat{y}_i, y_i): the per example loss is the negative log likelihood, =logp(yixi;w)\ell = -\log p(y_i \mid x_i; w).

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 y=wx+εy = w^\top x + \varepsilon with εN(0,σ2)\varepsilon \sim \mathcal{N}(0, \sigma^2), so

p(yx;w)=12πσ2exp ⁣((ywx)22σ2).p(y \mid x; w) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp\!\left(-\frac{(y - w^\top x)^2}{2\sigma^2}\right).

Take the negative log of one term:

logp(yx;w)=(ywx)22σ2+12log(2πσ2)constant in w.-\log p(y \mid x; w) = \frac{(y - w^\top x)^2}{2\sigma^2} + \underbrace{\tfrac{1}{2}\log(2\pi\sigma^2)}_{\text{constant in } w}.

The additive constant doesn't affect the minimizer, and the factor 1/σ21/\sigma^2 is a positive constant that only rescales now drop both, and you're minimizing i(yiwxi)2\sum_i (y_i - w^\top x_i)^2. 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 logp^y-\log \hat{p}_y which is the cross-entropy from the previous section.

Derivation: categorical labels ⟹ cross-entropy

For a KK-class label, assume yy is drawn from a categorical distribution with p(y=kx)=p^kp(y = k \mid x) = \hat{p}_k, where p^=softmax(scores)\hat{\mathbf{p}} = \text{softmax}(\text{scores}). Using the one-hot encoding of the true label, the probability of the observed class is

k=1Kp^k1[y=k]=p^y.\prod_{k=1}^{K} \hat{p}_k^{\,\mathbb{1}[y=k]} = \hat{p}_y.

The negative log-likelihood of one example is therefore

logp(yx;w)=logp^y,-\log p(y \mid x; w) = -\log \hat{p}_y,

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

Gradients and Contours ascent or descent 2D

We now have a loss L(w)\mathcal{L}(w) 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 ww, 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 (w,x,h\mathbf{w}, \mathbf{x}, \mathbf{h}) are vectors; capitals (X,H,QX, H, Q) are matrices; plain lowercase (η,λ,κ\eta, \lambda, \kappa) are scalars. A subscript picks out an entry: wjw_j is the jj-th component of w\mathbf{w}.

One dimension: the derivative

For a function of a single variable L(w)L(w), the derivative is the local slope:

dLdw=limh0L(w+h)L(w)h\frac{dL}{dw} = \lim_{h \to 0} \frac{L(w + h) - L(w)}{h}

It answers: if I nudge ww a little, how fast does LL change? It carries two pieces of info :

Many dimensions: partial derivatives

Now let L:RdRL : \mathbb{R}^d \to \mathbb{R} be the loss as a function of all dd weights w=(w1,,wd)\mathbf{w} = (w_1, \dots, w_d)^\top. 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:

Lwj=limh0L(w1,,wj+h,,wd)L(w1,,wd)h\frac{\partial L}{\partial w_j} = \lim_{h \to 0} \frac{L(w_1, \dots, w_j + h, \dots, w_d) - L(w_1, \dots, w_d)}{h}

In words: hold every weight fixed except wjw_j, nudge only wjw_j, 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 L(w1,w2)=w12+3w1w2L(w_1, w_2) = w_1^2 + 3 w_1 w_2:

Lw1=2w1+3w2,Lw2=3w1\frac{\partial L}{\partial w_1} = 2 w_1 + 3 w_2, \qquad \frac{\partial L}{\partial w_2} = 3 w_1

Stacking them: the gradient

The gradient collects all dd partial derivatives into a single vector:

L(w)=(Lw1Lwd)Rd\nabla L(\mathbf{w}) = \begin{pmatrix} \dfrac{\partial L}{\partial w_1} \\[6pt] \vdots \\[4pt] \dfrac{\partial L}{\partial w_d} \end{pmatrix} \in \mathbb{R}^d

Why this particular vector matters

The gradient compresses all directional information into one object. Take a small step h\mathbf{h} from w\mathbf{w} and ask how LL changes. The first-order Taylor expansion says:

L(w+h)L(w)+L(w)hL(\mathbf{w} + \mathbf{h}) \approx L(\mathbf{w}) + \nabla L(\mathbf{w})^\top \mathbf{h}

So the change in LL under any direction of movement is just an inner product with the gradient. Now use the geometric form of the inner product, Lh=Lhcosθ\nabla L^\top \mathbf{h} = \|\nabla L\|\,\|\mathbf{h}\|\cos\theta, and sweep over all unit directions h\mathbf{h}:

One consequence: at a minimum, no direction decreases LL, which forces

L(w)=0.\nabla L(\mathbf{w}^*) = \mathbf{0}.

"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 ddw(bw)=b\frac{d}{dw}(bw) = b and ddw(aw2)=2aw\frac{d}{dw}(a w^2) = 2aw. Everything reduces to the coordinate-wise partials above plus careful indexing.

Identity 1: w(bw)=b\nabla_\mathbf{w}(\mathbf{b}^\top \mathbf{w}) = \mathbf{b}.

Write it out: bw=kbkwk\mathbf{b}^\top \mathbf{w} = \sum_k b_k w_k. Take the partial with respect to wjw_j — every term dies except bjwjb_j w_j:

wjkbkwk=bjw(bw)=b.\frac{\partial}{\partial w_j} \sum_k b_k w_k = b_j \quad\Longrightarrow\quad \nabla_\mathbf{w}(\mathbf{b}^\top \mathbf{w}) = \mathbf{b}.

Identity 2: w(wAw)=2Aw\nabla_\mathbf{w}(\mathbf{w}^\top A \mathbf{w}) = 2 A \mathbf{w} for symmetric AA.

Expand: wAw=klAklwkwl\mathbf{w}^\top A \mathbf{w} = \sum_k \sum_l A_{kl} w_k w_l. Take /wj\partial/\partial w_j; the variable wjw_j appears when k=jk = j and when l=jl = j:

wjk,lAklwkwl=lAjlwlk=j+kAkjwkl=j=(Aw)j+(Aw)j.\frac{\partial}{\partial w_j} \sum_{k,l} A_{kl} w_k w_l = \underbrace{\sum_l A_{jl} w_l}_{k = j} + \underbrace{\sum_k A_{kj} w_k}_{l = j} = (A\mathbf{w})_j + (A^\top \mathbf{w})_j.

So in general w(wAw)=(A+A)w\nabla_\mathbf{w}(\mathbf{w}^\top A \mathbf{w}) = (A + A^\top)\mathbf{w}, and when AA is symmetric (A=AA^\top = A) this collapses to 2Aw2 A \mathbf{w}. (We'll only ever apply this to A=XXA = X^\top X, 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 L-\nabla L, take a step that way, repeat.

wt+1=wtηL(wt)\mathbf{w}_{t+1} = \mathbf{w}_t - \eta\,\nabla L(\mathbf{w}_t)

L(wt)\nabla L(\mathbf{w}_t) is the locally steepest uphill direction; the minus sign flips it downhill; η\eta (the learning rate) scales how far we move; and we repeat until L0\nabla L \approx \mathbf{0}, i.e. until no direction goes downhill anymore.

The learning rate is delicate

Gradient descent

That single number η\eta controls everything, and picking it badly breaks training. On the same loss surface, four regimes:




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 XwX\mathbf{w} (the design matrix XX times the weights):

L(w)=12nXwy22=12n(Xwy)(Xwy)\mathcal{L}(\mathbf{w}) = \frac{1}{2n}\|X\mathbf{w} - \mathbf{y}\|_2^2 = \frac{1}{2n}(X\mathbf{w} - \mathbf{y})^\top(X\mathbf{w} - \mathbf{y})

Expand and differentiate using the two identities from earlier (this is where the 12\frac{1}{2} we carried since the squared-loss definition it cancels the 2 from the derivative):

L(w)=1n(XXwXy)\nabla \mathcal{L}(\mathbf{w}) = \frac{1}{n}\left(X^\top X \mathbf{w} - X^\top \mathbf{y}\right)

Differentiate once more to get the Hessian which is the matrix of second partial derivatives, i.e. the derivative of the gradient:

2L=1nXX=:H\nabla^2 \mathcal{L} = \frac{1}{n} X^\top X =: H

Notice what did not happen: HH has no w\mathbf{w} in it. The Hessian is constant. That means L\mathcal{L} is exactly a quadratic function — a dd-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 L=0\nabla \mathcal{L} = \mathbf{0} gives the Normal Equation:

XXw=XyX^\top X \mathbf{w}^* = X^\top \mathbf{y}

Now a small trick that makes everything downstream trivial. Since Xy=XXwX^\top \mathbf{y} = X^\top X \mathbf{w}^*, substitute it back into the gradient:

L(w)=1nXX(ww)=H(ww)\nabla \mathcal{L}(\mathbf{w}) = \frac{1}{n}X^\top X(\mathbf{w} - \mathbf{w}^*) = H(\mathbf{w} - \mathbf{w}^*)

The gradient is a linear function of the error ww\mathbf{w} - \mathbf{w}^*. Hold onto this line — it's the engine of the whole argument.

Eigenvalues are the curvatures of the bowl

H=1nXXH = \frac{1}{n}X^\top X is symmetric and positive (semi-)definite, so by the spectral theorem it has an orthonormal eigendecomposition:

H=QΛQ,Λ=diag(λ1,,λd),λ1λd>0H = Q \Lambda Q^\top, \qquad \Lambda = \mathrm{diag}(\lambda_1, \dots, \lambda_d), \quad \lambda_1 \ge \dots \ge \lambda_d > 0

where the columns q1,,qd\mathbf{q}_1, \dots, \mathbf{q}_d of QQ are orthonormal eigenvectors. What does an eigenvalue mean here? Step a distance tt away from the minimum along eigendirection qi\mathbf{q}_i and measure the loss (exact, since L\mathcal{L} is quadratic):

L(w+tqi)=L(w)+λi2t2\mathcal{L}(\mathbf{w}^* + t\,\mathbf{q}_i) = \mathcal{L}(\mathbf{w}^*) + \frac{\lambda_i}{2} t^2

So along qi\mathbf{q}_i the loss is a 1-D parabola with curvature λi\lambda_i. Large λi\lambda_i = steep, tight valley wall; small λi\lambda_i = nearly flat floor. The level sets {w:L(w)=c}\{\mathbf{w} : \mathcal{L}(\mathbf{w}) = c\} are ellipsoids whose axis along qi\mathbf{q}_i has length proportional to 1/λi1/\sqrt{\lambda_i}. If λ1=106\lambda_1 = 10^6 and λ2=1\lambda_2 = 1, the ellipse is 1000×1000\times 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:

κ=λmaxλmin=λ1λd1\kappa = \frac{\lambda_{\max}}{\lambda_{\min}} = \frac{\lambda_1}{\lambda_d} \ge 1

κ=1\kappa = 1 is a perfectly round bowl; κ=106\kappa = 10^6 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 et:=wtw\mathbf{e}_t := \mathbf{w}_t - \mathbf{w}^*:

wt+1=wtηH(wtw)et+1=(IηH)et\mathbf{w}_{t+1} = \mathbf{w}_t - \eta H(\mathbf{w}_t - \mathbf{w}^*) \quad\Longrightarrow\quad \mathbf{e}_{t+1} = (I - \eta H)\,\mathbf{e}_t

The error just gets multiplied by the fixed matrix IηHI - \eta H every step. Change basis to the eigenvectors — let e~t(i)=qiet\tilde{e}_t^{(i)} = \mathbf{q}_i^\top \mathbf{e}_t be the component of the error along eigendirection ii. Because Q(IηH)Q=IηΛQ^\top (I - \eta H) Q = I - \eta \Lambda is diagonal, the directions stop interacting:

e~t+1(i)=(1ηλi)e~t(i)  e~t(i)=(1ηλi)te~0(i)  \tilde{e}_{t+1}^{(i)} = (1 - \eta \lambda_i)\,\tilde{e}_t^{(i)} \quad\Longrightarrow\quad \boxed{\;\tilde{e}_t^{(i)} = (1 - \eta \lambda_i)^t\, \tilde{e}_0^{(i)}\;}

This is the whole story in one line. Gradient descent on a quadratic decouples into dd independent 1-D problems, one per eigendirection, each shrinking geometrically at its own rate 1ηλi|1 - \eta \lambda_i|. There is no cross-talk between directions.

The divergence cliff, explained

Direction ii converges if and only if 1ηλi<1|1 - \eta \lambda_i| < 1, which rearranges to 0<η<2/λi0 < \eta < 2/\lambda_i. This must hold for every direction at once, and the binding constraint is the largest eigenvalue:

η<2λmax\eta < \frac{2}{\lambda_{\max}}

There is the cliff from the previous section. If η2/λmax\eta \ge 2/\lambda_{\max}, the component along the steepest direction q1\mathbf{q}_1 has 1ηλmax1|1 - \eta \lambda_{\max}| \ge 1, 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 η\eta crossing 2/λmax2/\lambda_{\max}.

The speed limit

Here's the tension. You'd love to crank η\eta up to make the slowest direction (rate 1ηλmin|1 - \eta\lambda_{\min}|) converge faster — but the steep direction caps you at η<2/λmax\eta < 2/\lambda_{\max}. The best you can do is balance them. Minimizing the worst-case contraction rate over all directions gives the optimal step size and rate:

η=2λmax+λmin,ρ(η)=λmaxλminλmax+λmin=κ1κ+1\eta^* = \frac{2}{\lambda_{\max} + \lambda_{\min}}, \qquad \rho(\eta^*) = \frac{\lambda_{\max} - \lambda_{\min}}{\lambda_{\max} + \lambda_{\min}} = \frac{\kappa - 1}{\kappa + 1}
Where η* and the (κ−1)/(κ+1) rate come from

The worst-case contraction over all directions is ρ(η)=maxi1ηλi=max{1ηλmin, 1ηλmax}\rho(\eta) = \max_i |1 - \eta\lambda_i| = \max\{|1 - \eta\lambda_{\min}|,\ |1 - \eta\lambda_{\max}|\} (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:

1ηλmin=(1ηλmax)    2=η(λmin+λmax)    η=2λmax+λmin.1 - \eta^*\lambda_{\min} = -(1 - \eta^*\lambda_{\max}) \;\Longrightarrow\; 2 = \eta^*(\lambda_{\min} + \lambda_{\max}) \;\Longrightarrow\; \eta^* = \frac{2}{\lambda_{\max} + \lambda_{\min}}.

Substituting back:

ρ(η)=12λminλmax+λmin=λmaxλminλmax+λmin=κ1κ+1.\rho(\eta^*) = 1 - \frac{2\lambda_{\min}}{\lambda_{\max} + \lambda_{\min}} = \frac{\lambda_{\max} - \lambda_{\min}}{\lambda_{\max} + \lambda_{\min}} = \frac{\kappa - 1}{\kappa + 1}.
So every step, the error shrinks by *at best* a factor $\frac{\kappa - 1}{\kappa + 1}$. To reach a target error $\epsilon$ you need roughly tκ2ln ⁣e0ϵ=O(κ)t \approx \frac{\kappa}{2}\ln\!\frac{\|\mathbf{e}_0\|}{\epsilon} = O(\kappa)

iterations. The number of steps scales linearly with the condition number. κ=106\kappa = 10^6 means on the order of a million iterations where a round bowl (κ1\kappa \approx 1) 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 ϵ\epsilon we need ρte0ϵ\rho^t \|\mathbf{e}_0\| \le \epsilon, i.e. tln(e0/ϵ)lnρt \ge \frac{\ln(\|\mathbf{e}_0\|/\epsilon)}{-\ln \rho}. For large κ\kappa, write ρ=κ1κ+1=12κ+1\rho = \frac{\kappa - 1}{\kappa + 1} = 1 - \frac{2}{\kappa + 1} and use ln(1x)x\ln(1 - x) \approx -x for small xx:

lnρ2κ+12κtκ2lne0ϵ.-\ln\rho \approx \frac{2}{\kappa + 1} \approx \frac{2}{\kappa} \quad\Longrightarrow\quad t \approx \frac{\kappa}{2}\ln\frac{\|\mathbf{e}_0\|}{\epsilon}.
### Closing the loop: this is why we normalize

Now the payoff. Where does a large κ\kappa actually come from? Look at the entries of H=1nXXH = \frac{1}{n}X^\top X:

Hjk=1ni=1nxijxik,soHjj=1nixij2H_{jk} = \frac{1}{n}\sum_{i=1}^n x_{ij}\, x_{ik}, \qquad \text{so} \qquad H_{jj} = \frac{1}{n}\sum_i x_{ij}^2

The diagonal entry HjjH_{jj} is the mean squared magnitude of feature jj. Feature scales sit directly on the Hessian's diagonal. Take two uncorrelated features — house size (103\sim 10^3, so H11106H_{11} \approx 10^6) and bedroom count (3\sim 3, so H2210H_{22} \approx 10). With no correlation, HH is diagonal, its eigenvalues are those diagonal entries, and

κ10610=105.\kappa \approx \frac{10^6}{10} = 10^5.

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 Hjj=1H_{jj} = 1, and 1nXX\frac{1}{n}X^\top X becomes the feature correlation matrix. If the features are roughly uncorrelated that's approximately the identity, whose eigenvalues are all 1 — so κ1\kappa \approx 1, 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 κ\kappa: for correlation rr, the 2×22\times 2 correlation matrix has eigenvalues 1+r1 + r and 1r1 - r, so κ=1+r1r\kappa = \frac{1+r}{1-r} \to \infty as r1r \to 1. 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.