Neural network formulas: a cheat sheet · Losses — regression

MSE: the mean squared error

The main loss of regression and the foundation of least squares. We take MSE apart bone by bone: literal squares on the errors, why the mean minimizes it, the derivative 2e and the bowl over the model’s parameters, the critical step of gradient descent, the bias–variance decomposition, the link with Gaussian noise and the sensitivity to outliers.

Javharbek Abdulatipov · 35 min read
$$\mathrm{MSE}=\frac{1}{n}\sum_{i=1}^{n}\bigl(y_i-\hat{y}_i\bigr)^2$$

Why we need it

If a model predicts a number, it was almost certainly trained by reducing MSE, the mean squared error. It is the “default” loss for regression: it has an exact solution for linear models, a smooth gradient for neural networks and a clear statistical meaning. The method of least squares, published by Legendre in 1805 and tied to the normal law of errors by Gauss in 1809, is exactly the minimization of MSE.

Where it appears:

  • linear regression — ordinary least squares (OLS) with a one-formula solution;
  • neural networks for regression — MSELoss in PyTorch, "mse" in Keras; autoencoders that reconstruct their input;
  • diffusion models — the network learns to predict the added noise, and the loss is the MSE between the true and the predicted noise;
  • reinforcement learning — the value function is often trained on the squared TD error;
  • gradient boosting — loss="squared_error": the negative gradient of MSE is the residual, so every tree is fitted to the residuals;
  • signal and image processing — PSNR is computed from MSE, and the Kalman filter minimizes the expected squared error.
The essentials in a minute

MSE is the mean of the squared errors: $\frac1n\sum(y_i-\hat y_i)^2$. The square turns the loss into a smooth bowl with a single bottom, its gradient $-\frac2n(y_i-\hat y_i)$ is proportional to the error, and the best constant is the mean. The flip side is that the square inflates big misses: one error of 10 weighs as much as a hundred errors of 1, so MSE is sensitive to outliers and is measured in squared units.

Intuition: the area of the squares

The word “squared” can be taken literally here. Draw a square with side $|e_i|$ on each error. Its area is $e_i^2$, and MSE is the average area of the squares. Compare with MAE, where lengths of segments are averaged: area grows as the square of the side, so big errors take up a disproportionate amount of space.

Below is the cheat sheet’s running example: $y=(3,\,5,\,8)$, $\hat y=(2.5,\,5,\,10)$. Drag the blue predictions. On the lower plot the errors sit on the parabola $e^2$; MSE is the average height of these points.

Figure 1. The squared errors of the running example. The areas are $0.25$, $0$ and $4$; the sum is $4.25$ and $\mathrm{MSE}=4.25/3\approx1.417$. The third square is $94\%$ of the total area. Move the third prediction to $8$ and MSE drops to $0.25/3\approx0.083$.
What to notice

The error $2$ is 4 times the error $0.5$, but its square is 16 times larger. A model trained on MSE is therefore “afraid” of big misses and readily trades several small errors for removing one large one. That is both a virtue (big errors are usually more costly) and a weakness (an outlier in the data also looks like a “big error”).

The formula, bone by bone

The same four steps as in MAE, only with a square instead of the absolute value.

$$\underbrace{y_i-\hat y_i}_{\text{error }e_i}\;\longrightarrow\;\underbrace{e_i^2}_{\text{area}}\;\longrightarrow\;\underbrace{\sum_{i=1}^{n}e_i^2}_{\text{SSE}}\;\longrightarrow\;\underbrace{\frac1n\sum_{i=1}^{n}e_i^2}_{\text{MSE}}$$
$y_i$
the true value for object $i$;
$\hat y_i$
the model’s prediction;
$e_i=y_i-\hat y_i$
the error (residual); its sign disappears after squaring;
$e_i^2$
the square: non-negative, smooth, and growing faster the larger the error;
$\sum e_i^2$
the sum of squared residuals — SSE (sum of squared errors), or RSS (residual sum of squares);
$\frac1n$
averaging: MSE does not depend on the sample size.

Why a square and not the absolute value? There are three reasons. Smoothness: $e^2$ has the derivative $2e$ everywhere, including at zero. Algebra: a sum of squares is a quadratic form, and its minimum is found by solving a linear system (the normal equations). Geometry: $\sum e_i^2$ is a squared Euclidean distance, and the best prediction is an orthogonal projection, as in Pythagoras’ theorem.

$i$$y_i$$\hat y_i$$e_i$$e_i^2$share of the sum
132.50.50.255.9%
255000%
3810−2494.1%
Sum4.25100%
Mean (MSE)1.417

In vector form MSE is the squared Euclidean norm of the error vector divided by $n$:

$$\mathrm{MSE}(y,\hat y)=\frac{1}{n}\,\bigl\|y-\hat y\bigr\|_2^2,\qquad \mathrm{RMSE}=\sqrt{\mathrm{MSE}}$$

Hence its second name, the L2 loss. The units of MSE are the units of $y$ squared: roubles², minutes². To get back to the original units, take the square root and you get RMSE; in the example $\sqrt{1.417}\approx1.190$.

Properties and the best constant

  • Non-negativity: $\mathrm{MSE}\ge0$, with equality only for exact predictions.
  • Quadratic scaling: multiply $y$ and $\hat y$ by $k$ and MSE is multiplied by $k^2$. Converting roubles to thousands of roubles shrinks MSE a million times.
  • Smoothness and convexity: MSE is a quadratic function of the predictions; for a linear model, a quadratic function of the parameters. If the columns of the feature matrix (together with the column of ones for the intercept) are linearly independent, it is strictly convex and the minimum is unique.
  • Error decomposition: $\mathrm{MSE}=\bar e^{\,2}+\operatorname{Var}(e)$ — the squared mean bias plus the spread of the errors. In the example $\bar e=-0.5$: $1.417=0.25+1.167$.
  • Comparison with MAE: $\mathrm{MSE}\ge\mathrm{MAE}^2$ (the mean of squares is at least the square of the mean). In the example: $1.417\ge0.833^2\approx0.694$.

The best constant is the mean

If the model answers with a single number $c$, MSE as a function of $c$ is a parabola. Expand it by adding and subtracting the mean $\bar y$:

$$\mathrm{MSE}(c)=\frac1n\sum_{i=1}^{n}(y_i-c)^2=\underbrace{\frac1n\sum_{i=1}^{n}(y_i-\bar y)^2}_{\operatorname{Var}(y)}+\;(c-\bar y)^2$$

The first term does not depend on $c$; the second is non-negative and vanishes only at $c=\bar y$. So the minimum of MSE is unique and is attained at the mean, and its value is the variance of the data. The derivative $2(c-\bar y)$ is a straight line proportional to the distance from the mean.

Figure 2. $\mathrm{MSE}(c)$ for the sample $(2,\,3,\,5,\,9,\,16)$ and its derivative. The mean is $\bar y=7$ and the minimum is $\operatorname{Var}=26$. At $c=12$: $\mathrm{MSE}=26+(12-7)^2=51$, and the derivative is $2\cdot5=10$. The median $5$ gives $30$ — under MSE it is worse than the mean. Turn on the outlier ($16\to40$): the mean moves to $11.8$, the variance grows to $204.56$, while the median stays at $5$.
Proof of the decomposition MSE(c) = Var + (c − ȳ)²

Write $y_i-c=(y_i-\bar y)+(\bar y-c)$ and square it:

$$\sum_{i=1}^{n}(y_i-c)^2=\sum_{i=1}^{n}(y_i-\bar y)^2+2(\bar y-c)\sum_{i=1}^{n}(y_i-\bar y)+n(\bar y-c)^2$$

The middle term is zero because deviations from the mean sum to zero: $\sum(y_i-\bar y)=n\bar y-n\bar y=0$. Divide by $n$ to get the decomposition. The same algebra gives the formula $\mathrm{MSE}=\bar e^{\,2}+\operatorname{Var}(e)$ and, in its probabilistic version, the bias–variance decomposition.

Compare with MAE

For MAE the best constant is the median, which ignores the outlier. For MSE it is the mean, which the outlier drags along: one point moved by $\Delta$ moves the mean by $\Delta/n$, however large $\Delta$ is. The MAE page runs the same experiment for the median.

The derivative: a force proportional to the error

The derivative of the square is $2e$. The further the prediction is from the truth, the harder the gradient pulls it back, and at the minimum itself the force fades out smoothly. This is exactly what makes MSE so convenient for gradient descent.

Derivation: the derivative of MSE with respect to the predictions and the parameters

For one object $\ell=(y_i-\hat y_i)^2$. By the chain rule, with $\partial e_i/\partial\hat y_i=-1$:

$$\frac{\partial\,\mathrm{MSE}}{\partial\hat y_i}=\frac1n\cdot2e_i\cdot(-1)=-\frac{2}{n}\bigl(y_i-\hat y_i\bigr)$$

For a linear model $\hat y_i=wx_i+b$:

$$\frac{\partial\,\mathrm{MSE}}{\partial w}=-\frac2n\sum_{i=1}^{n}e_i\,x_i,\qquad \frac{\partial\,\mathrm{MSE}}{\partial b}=-\frac2n\sum_{i=1}^{n}e_i$$

In matrix form, with $\hat y=X\theta$: $\nabla_\theta\,\mathrm{MSE}=\frac2nX^\top(X\theta-y)$, and the Hessian $\frac2nX^\top X$ does not depend on $\theta$ — the curvature of the bowl is the same everywhere.

The second derivative with respect to each prediction is constant: $\partial^2\mathrm{MSE}/\partial\hat y_i^2=2/n$. That is why in gradient boosting on MSE the Newton step is simply the mean residual in a leaf, and each new tree is trained on the residuals $y_i-F(x_i)$.

$$\frac{\partial\,\mathrm{MSE}}{\partial\hat y_i}=-\frac{2}{n}\bigl(y_i-\hat y_i\bigr)$$

Look at gradient descent on a single error. The step $\hat y\leftarrow\hat y-\eta\,\partial e^2/\partial\hat y=\hat y+2\eta e$ turns the error into $e\leftarrow(1-2\eta)\,e$. Each step multiplies the error by the same number — a geometric progression.

Figure 3. On the left, the parabola $e^2$, the tangent at the starting point and the descent steps; on the right, the derivative $2e$: the lengths of the blue segments, i.e. the gradients, shrink together with the error. With $e_0=2.5$ and $\eta=0.3$ the factor is $1-2\eta=0.4$: the errors are $1$, $0.4$, $0.16$. Change the step: for $\eta<0.5$ the error decreases monotonically, at $\eta=0.5$ it vanishes in one step, for $0.5<\eta<1$ it decreases with oscillations, at $\eta=1$ it swings forever, and for $\eta>1$ it grows.
Compare with MAE

For $|e|$ the derivative $\pm1$ does not depend on the size of the error, so steps with a constant $\eta$ do not get shorter and the descent jitters around the minimum (see MAE). For $e^2$ the “brakes” are built in: the gradient shrinks by itself near the bottom, and a constant step is enough for exact convergence.

The bowl over the parameters: least squares and gradient descent

Take the line $\hat y=wx+b$ and five points: $x=(1,\,2,\,3,\,4,\,5)$, $y=(1.3,\,2,\,3.1,\,4.5,\,7)$. MSE as a function of $(w,\,b)$ is a quadratic form, and its graph is an elliptic bowl (a paraboloid) with a single bottom.

The exact solution: the normal equations

Setting the gradient to zero gives a linear system — the normal equations — and the least-squares solution:

$$X^\top X\,\theta=X^\top y\quad\Longrightarrow\quad\theta^*=(X^\top X)^{-1}X^\top y;\qquad w^*=\frac{\operatorname{Cov}(x,y)}{\operatorname{Var}(x)},\quad b^*=\bar y-w^*\bar x$$

For our points $w^*=1.39$, $b^*=-0.59$, $\mathrm{MSE}^*=0.2294$. In practice the inverse matrix is not computed: QR or SVD decompositions are used (np.linalg.lstsq), and on large data, gradient descent.

Gradient descent and the shape of the bowl

The speed of descent is set by the shape of the bowl — the eigenvalues of the Hessian $H=\frac2nX^\top X$. Along the steep direction ($\lambda_{\max}$) too large a step throws you over the bottom; along the flat one ($\lambda_{\min}$) the descent crawls. For our data $\lambda_{\max}=23.66$ and $\lambda_{\min}=0.338$; their ratio, the condition number, is about $70$: the bowl is stretched into a narrow ravine, and any step above $\eta_{\text{crit}}=2/\lambda_{\max}\approx0.0845$ diverges.

Figure 4. On the left, the bowl $\mathrm{MSE}(w,b)$ (you can rotate it); on the right, the view from above and the excess over the minimum on a log scale. The start is the line $y=3$, $\eta=0.05$. In 150 steps the descent gets down the ravine only to an excess of $1.5\cdot10^{-2}$; at $\eta=0.09$ it blows up. Switch to the centred feature $x-\bar x$: the Hessian becomes diagonal ($\lambda=4$ and $2$), the condition number drops to $2$, the admissible step grows to $0.5$, and with the same $\eta=0.05$ the excess is below $10^{-6}$ already at step 61, and at $\eta=0.2$ at step 13.
Why the convergence condition is η < 2/λ_max

For a quadratic function the gradient is linear: $\nabla\mathrm{MSE}(\theta)=H(\theta-\theta^*)$. A descent step gives

$$\theta_{t+1}-\theta^*=(I-\eta H)(\theta_t-\theta^*)\quad\Longrightarrow\quad\theta_t-\theta^*=(I-\eta H)^t(\theta_0-\theta^*)$$

In the eigenbasis of $H$ each coordinate is multiplied by $1-\eta\lambda_k$ at every step. The descent converges if $|1-\eta\lambda_k|<1$ for all $k$, i.e. $0<\eta<2/\lambda_{\max}$. For $1/\lambda_{\max}<\eta<2/\lambda_{\max}$ the factor is negative — hence the zigzag across the ravine. The slowest direction is $\lambda_{\min}$: even with the best constant step $\eta=2/(\lambda_{\max}+\lambda_{\min})$ the error shrinks by a factor $(\kappa-1)/(\kappa+1)$ per step, where $\kappa=\lambda_{\max}/\lambda_{\min}$. At $\kappa=70$ that is $0.97$ — hundreds of steps; at $\kappa=2$ it is $1/3$.

The practical takeaway

Standardize the features (subtract the mean, divide by the standard deviation): this rounds the bowl and allows a larger step. Adaptive optimizers (Adam, RMSProp) do a similar rescaling automatically, but only coordinate by coordinate: a ravine tilted relative to the axes, like ours, is straightened only partly.

Bias and variance

MSE on new data splits into three parts, and this is perhaps the most important formula about overfitting. Let $y=f(x)+\varepsilon$, where the noise has mean $0$ and variance $\sigma^2$, and let the model $\hat f$ be trained on a random sample. Then the expected error at a point $x$ is:

$$\mathbb E\bigl[(y-\hat f(x))^2\bigr]=\underbrace{\bigl(f(x)-\mathbb E\hat f(x)\bigr)^2}_{\text{bias}^2}+\underbrace{\mathbb E\bigl[(\hat f(x)-\mathbb E\hat f(x))^2\bigr]}_{\text{variance}}+\underbrace{\sigma^2}_{\text{noise}}$$
$\mathbb E\hat f(x)$
the average prediction over all possible training samples;
$\text{bias}^2$
how far the average model misses the truth — the price of a too simple model;
$\text{variance}$
how much the model changes from sample to sample — the price of a too flexible model;
$\sigma^2$
irreducible noise: no model can remove it.
Figure 5. The truth $f(x)=\sin\pi x$, 15 points with noise $\sigma=0.3$, 200 different training samples, polynomials of degree $d$. A line ($d=1$) is biased: $0.204+0.012+0.09=0.306$. At $d=3$ the expected error is minimal: $0.005+0.025+0.09=0.120$. At $d=10$ the bias barely changes ($0.005$), but the variance shoots up to $0.777$ and the test MSE is $0.872$, even though the training MSE is only $0.022$ — less than the noise itself, $\sigma^2=0.09$: the model memorizes the noise.
Deriving the decomposition

Denote $\bar f=\mathbb E\hat f(x)$. The noise $\varepsilon$ at a new point does not depend on the training sample, so

$$\mathbb E(y-\hat f)^2=\mathbb E(f+\varepsilon-\hat f)^2=\sigma^2+\mathbb E(f-\hat f)^2$$

Then repeat the trick from the section on the constant: $f-\hat f=(f-\bar f)+(\bar f-\hat f)$, and the cross term vanishes because $\mathbb E(\bar f-\hat f)=0$:

$$\mathbb E(f-\hat f)^2=(f-\bar f)^2+\mathbb E(\hat f-\bar f)^2$$

In the figure the same quantities are averaged over a uniform grid $x\in[-1,\,1]$. Even degrees add almost nothing for the odd function $\sin\pi x$: the bias at $d=1$ and $d=2$ is the same.

A biased estimate can be better

What has to be minimized is the sum, not the bias alone. Regularization (ridge regression, early stopping, model averaging) deliberately introduces bias to reduce variance even more, and often lowers the test MSE.

The probabilistic meaning: Gaussian noise

Why the square of all things? The classical answer was given by Gauss (1809). Let $y_i=\hat y_i+\varepsilon_i$, where the noise $\varepsilon_i$ is independent and normally distributed, $N(0,\sigma^2)$. The density of one observation is a bell around the prediction, and the likelihood of the sample is the product of the heights of the bells at the data points. The negative log-likelihood is:

$$-\ln L=\frac n2\ln(2\pi\sigma^2)+\frac{1}{2\sigma^2}\sum_{i=1}^{n}\bigl(y_i-\hat y_i\bigr)^2=\frac n2\ln(2\pi\sigma^2)+\frac{n}{2\sigma^2}\,\mathrm{MSE}$$

For any fixed $\sigma$ this is an increasing linear function of MSE. Hence minimizing MSE is maximum likelihood under Gaussian noise. Minimizing over $\sigma$ gives one more link: $\hat\sigma^2=\mathrm{MSE}$. Later (1821–1823) Gauss gave a second justification that needs no normality: if the errors are unbiased, uncorrelated and have equal variance, the least-squares estimate has the smallest variance among all linear unbiased estimates (the Gauss–Markov theorem).

Figure 6. On the left, a line and the normal bells $N(\hat y_i,\sigma^2)$ around it; the orange segments are the heights of the bells at the data points, i.e. each point’s contribution to the likelihood. On the right, $-\ln L$ as a function of MSE at the current $\sigma$: a straight line. For $w=1$, $b=0.5$, $\sigma=0.6$: $\mathrm{MSE}=0.540$ and $-\ln L=5.791$; the least-squares line (red point) with $\mathrm{MSE}=0.229$ gives $-\ln L=3.634$. The best $\sigma$ for the current line is $\sqrt{0.54}\approx0.735$.

One more statement of the same fact: among all functions $g(x)$ the expected squared error $\mathbb E(y-g(x))^2$ is smallest for $g(x)=\mathbb E[y\mid x]$. A model trained on MSE estimates the conditional mean. If the noise is asymmetric or heavy-tailed, the conditional mean can describe the “typical” outcome poorly — then one looks at the median (MAE) or at quantiles.

Outliers: unbounded influence

The flip side of the square is sensitivity to anomalous points. The gradient from an object is proportional to its error, so a distant outlier pulls the model harder the further away it is. Robust statistics says that least squares has an unbounded influence function and a breakdown point of zero: a single point is enough to drive the line arbitrarily far.

Figure 7. Ten points around $y=1+0.5x$ and an outlier at $x=9$. With the outlier at $y=0$ the slope of the MSE line drops to $0.291$, and the outlier alone accounts for $74\%$ of the sum of squares. On the right, the slope as a function of the outlier’s height: for MSE it is a straight line (each unit of height changes the slope by $0.0375$, from $0.104$ at $y=-5$ to $0.779$ at $y=13$), while for MAE the slope stays between $0.438$ and $0.514$.

What to do about outliers if you need MSE:

  • replace the loss with Huber: a square for small errors and the absolute value for large ones — the smoothness of MSE and the bounded influence of MAE;
  • transform the target ($\log y$ for prices and incomes) — but then the model estimates the mean of the logarithm, not the mean of $y$;
  • find and inspect outliers by their residuals: points with a huge $e_i^2$ stand out immediately;
  • use robust fitting algorithms (RANSAC, Theil–Sen) that learn from subsets of the data.

In code

MSE and its gradient in NumPy, the exact least-squares solution, and a check that the best constant is the mean:

pythonimport numpy as np

y     = np.array([3.0, 5.0, 8.0])
y_hat = np.array([2.5, 5.0, 10.0])

def mse(y, y_hat):
    return np.mean((y - y_hat) ** 2)

def mse_grad(y, y_hat):
    # gradient w.r.t. the predictions: 2(ŷ − y) / n
    return 2 * (y_hat - y) / y.size

print(mse(y, y_hat))        # 1.4166666666666667
print(mse_grad(y, y_hat))   # [-0.33333333  0.          1.33333333]

# the least-squares line: the exact solution of the normal equations
x = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
t = np.array([1.3, 2.0, 3.1, 4.5, 7.0])
A = np.column_stack([x, np.ones_like(x)])
w, b = np.linalg.lstsq(A, t, rcond=None)[0]
print(round(w, 4), round(b, 4), round(mse(t, A @ [w, b]), 4))   # 1.39 -0.59 0.2294

# the best constant under MSE is the mean; MSE(c) = Var + (c − ȳ)²
data = np.array([2.0, 3.0, 5.0, 9.0, 16.0])
print(data.mean(), mse(data, data.mean()), mse(data, 12.0))   # 7.0 26.0 51.0

In PyTorch it is MSELoss. The gradient with respect to the predictions is $2(\hat y-y)/n$; descent with step $0.05$ on the raw feature from Figure 4 reaches the same least-squares solution, but slowly: to two decimals it takes about 300 steps (the listing runs 2000 to be safe):

pythonimport torch
import torch.nn as nn

y     = torch.tensor([3.0, 5.0, 8.0])
y_hat = torch.tensor([2.5, 5.0, 10.0], requires_grad=True)

loss = nn.MSELoss()(y_hat, y)    # same as ((y_hat - y) ** 2).mean()
loss.backward()
print(loss.item())               # 1.4166666269302368
print(y_hat.grad)                # tensor([-0.3333,  0.0000,  1.3333])

# gradient descent for a line: with η > 2/λ_max ≈ 0.0845 it diverges
x = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0])
t = torch.tensor([1.3, 2.0, 3.1, 4.5, 7.0])
w = torch.zeros(1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)
opt = torch.optim.SGD([w, b], lr=0.05)
for step in range(2000):
    opt.zero_grad()
    nn.functional.mse_loss(w * x + b, t).backward()
    opt.step()
print(round(w.item(), 2), round(b.item(), 2))   # 1.39 -0.59

scikit-learn has MSE and RMSE metrics (the regressors’ score method returns $R^2$, though), LinearRegression minimizes MSE exactly, and boosting uses it as the default loss:

pythonimport numpy as np
from sklearn.metrics import mean_squared_error, root_mean_squared_error
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import HistGradientBoostingRegressor

print(mean_squared_error([3, 5, 8], [2.5, 5, 10]))        # 1.4166666666666667
print(root_mean_squared_error([3, 5, 8], [2.5, 5, 10]))   # 1.1902380714238083

X = np.array([[1.0], [2.0], [3.0], [4.0], [5.0]])
y = np.array([1.3, 2.0, 3.1, 4.5, 7.0])
lr = LinearRegression().fit(X, y)                    # minimizes MSE exactly
print(lr.coef_.round(4), round(lr.intercept_, 4))    # [1.39] -0.59

# boosting on MSE: each tree is fitted to the residuals y − F(x)
gbr = HistGradientBoostingRegressor(loss="squared_error")
The rule

Train on MSE, but in reports show RMSE (same units as $y$) next to MAE. A large gap between them signals a heavy tail or outliers in the errors.

Common mistakes

  1. Reading MSE as the “average error”. MSE $=1.417$ in the example is in squared units; the average error is of order $\sqrt{1.417}\approx1.19$ (RMSE) or $0.833$ (MAE).
  2. MSE on data with outliers. A few anomalies will drag the model along (Figure 7). Clean the data, or use Huber or MAE.
  3. Unscaled features. A stretched bowl means slow descent and a small admissible step (Figure 4). Standardize the features.
  4. Too large a step. With $\eta>2/\lambda_{\max}$ the loss grows exponentially and quickly turns into inf and nan.
  5. MSE for classification on top of a sigmoid. The gradient $2(p-y)\,p(1-p)$ vanishes when the model is confidently wrong ($p\approx0$ for $y=1$). For probabilities use BCE or cross-entropy.
  6. Judging a model by its training MSE. A low MSE on the training data can mean memorized noise (Figure 5, $d=10$). Look at validation.
  • MAE: the absolute value instead of the square — the median instead of the mean, robustness to outliers, but a kink at zero.
  • RMSE: $\sqrt{\mathrm{MSE}}$ — the same optimal model, but the error in the units of $y$.
  • Huber: MSE near zero and MAE in the tails.
  • BCE: the analogue of MSE for probabilities — also maximum likelihood, but for the Bernoulli distribution.
  • SGD and Adam: MSE shows clearly how the step and the conditioning of the problem determine convergence.

Summary

1) $\mathrm{MSE}=\frac1n\sum(y_i-\hat y_i)^2$ is the average area of the squares on the errors; $1.417$ in the example, with $94\%$ coming from a single error. 2) The best constant is the mean, and $\mathrm{MSE}(c)=\operatorname{Var}+(c-\bar y)^2$. 3) The gradient $-\frac2n(y_i-\hat y_i)$ is proportional to the error and fades by itself near the minimum. 4) For a linear model MSE is a bowl with the exact solution $(X^\top X)^{-1}X^\top y$; gradient descent converges for $\eta<2/\lambda_{\max}$, and its speed is set by the condition number. 5) Test MSE = bias² + variance + noise. 6) MSE is the likelihood under Gaussian noise; the model estimates the conditional mean. 7) The price is the unbounded influence of outliers.

Check yourself

1. $y=(1,\,4,\,6)$, $\hat y=(2,\,4,\,3)$. What is MSE?
2. Which constant minimizes MSE for the sample $(1,\,2,\,3,\,10,\,50)$?
3. What is $\partial\,\mathrm{MSE}/\partial\hat y_i$?
4. The eigenvalues of the MSE Hessian are $4$ and $2$. For which constant steps $\eta>0$ does gradient descent converge?
5. Minimizing MSE coincides with maximum likelihood if the noise is…