Neural network formulas: a cheat sheet · Losses — regression

RMSE: the root mean squared error

The most popular regression metric — and one of the most misread. We take it apart bone by bone: why the square root, what the gap between RMSE and MAE means, why RMSE is a distance between vectors, how it splits into bias and spread, and how its gradient differs from the gradient of MSE while the minimum stays the same.

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

Why it is needed

A model predicts the price of a flat, the demand for a product, tomorrow’s temperature. How do you say with a single number how wrong it is? A plain mean of the errors will not do: misses up and down cancel out. MSE squares the errors — but then the answer is in “dollars squared” or “degrees squared”, and “the MSE is 1,417,000” tells a client nothing. RMSE takes the square root and brings the error back to the units of the target, keeping everything people like about MSE.

Where it shows up:

  • evaluating regression models — one of the most common metrics in reports, papers and Kaggle competitions;
  • time-series forecasting — weather, demand, energy use; it usually sits next to MAE and MAPE;
  • recommender systems — the famous Netflix Prize (2006–2009) scored rating predictions by RMSE;
  • physics and metrology — the root-mean-square error of measurements, GPS accuracy, the “RMS” value of a signal;
  • training models — minimising RMSE and minimising MSE give the same model, but their gradients differ (see the section on the derivative).
The gist in a minute

RMSE is MSE under a square root: an error in the units of $y$ that, like MSE, punishes large misses harder. Always $\mathrm{MAE}\le\mathrm{RMSE}\le\sqrt n\,\mathrm{MAE}$, and $\mathrm{RMSE}^2=\bar r^{\,2}+\sigma_r^2$ — squared bias plus the variance of the residuals. The minimum of RMSE coincides with the minimum of MSE, and its gradient is the gradient of MSE divided by $2\,\mathrm{RMSE}$.

Intuition: the side of the mean square

Draw every error $r_i=y_i-\hat y_i$ as a square with side $|r_i|$. Its area $r_i^2$ is the object’s contribution to MSE. Add up the areas and divide by $n$ — that is the mean area, i.e. MSE. And RMSE is the side of the square whose area equals the mean area.

Drag the blue points — the forecasts. On the right all the error squares are nested in one corner: the blue square has side RMSE, the dashed teal one has side MAE.

Figure 1. The running example: $y=(3,\,5,\,8)$, $\hat y=(2.5,\,5,\,10)$. The error $-2$ gives a square of area 4, the error $0.5$ one of area $0.25$; the mean area is $\mathrm{MSE}\approx1.417$ and its side is $\mathrm{RMSE}\approx1.190$. The MAE side is shorter — $0.833$.
What to notice

A big square pulls the mean area harder than a long side pulls the mean length: the error $-2$ is $80\%$ of the sum of absolute values but $94\%$ of the sum of squares. That is why RMSE exceeds MAE — and the more uneven the errors, the larger the gap. Make all three errors equal in magnitude and the blue square will coincide with the teal one.

The formula bone by bone

Read the name from right to left and you get the recipe: the root of the mean of the squared error.

$$r_i=y_i-\hat y_i\;\xrightarrow{\;(\cdot)^2\;}\;r_i^2\ge0\;\xrightarrow{\;\frac1n\sum\;}\;\mathrm{MSE}\;\xrightarrow{\;\sqrt{\cdot}\;}\;\mathrm{RMSE}$$
$y_i$
the true value of the $i$-th object (the actual);
$\hat y_i$
the model’s forecast for that object;
$r_i=y_i-\hat y_i$
the error, or residual; its sign shows whether we under-estimated ($r_i>0$) or over-estimated ($r_i<0$);
$r_i^2$
squaring removes the sign and makes large errors disproportionately heavy: an error twice as large weighs four times as much;
$\frac1n\sum_{i=1}^n$
the mean over all $n$ objects is MSE, in squared units;
$\sqrt{\cdot}$
the root brings back the original units: if $y$ is in dollars, so is RMSE.

The running example step by step:

$i$$y_i$$\hat y_i$$r_i$$r_i^2$$|r_i|$
132.50.50.250.5
255000
3810−242
mean−0.51.4170.833
$$\mathrm{RMSE}=\sqrt{\frac{0.25+0+4}{3}}=\sqrt{1.417}\approx1.190,\qquad \mathrm{MAE}=\frac{0.5+0+2}{3}\approx0.833$$

It helps to recognise the same quantity in other forms:

$$\mathrm{RMSE}=\sqrt{\mathrm{MSE}}=\frac{\|y-\hat y\|_2}{\sqrt n}=M_2\bigl(|r_1|,\dots,|r_n|\bigr)$$

The second form is the Euclidean distance between the vector of actuals and the vector of forecasts divided by $\sqrt n$ (we will come back to it in 3D). The third is the quadratic mean (the power mean of order 2) of the absolute errors. MAE is their arithmetic mean $M_1$, and the largest error is the limiting case $M_\infty$. The power mean inequality immediately gives $\mathrm{MAE}\le\mathrm{RMSE}\le\max_i|r_i|$.

Why the square and not the absolute value

You can average absolute values — that is MAE. The square is chosen because it is smooth (differentiable everywhere), tied to variance and to the normal distribution (minimising MSE is maximum likelihood under Gaussian noise), and gives closed-form solutions (least squares). The root on top is only for readability: it does not change the ranking of models.

Properties

  • Non-negativity: $\mathrm{RMSE}\ge0$, and $\mathrm{RMSE}=0$ only for a perfect forecast $\hat y=y$.
  • Units — the same as those of $y$. Convert prices from thousands of dollars to dollars and RMSE grows exactly 1000 times: $\mathrm{RMSE}(c\,y,\,c\,\hat y)=|c|\,\mathrm{RMSE}(y,\hat y)$.
  • Shifts do not matter: add the same number to the actuals and the forecasts and RMSE stays the same. So RMSE does not say whether the error is large relative to the level of the series — that is what MAPE and normalised variants are for.
  • The same ranking as MSE: the root is strictly increasing, so comparing models by RMSE and by MSE always gives the same order, and both have their minimum at the same point.
  • Sensitivity to outliers: a single error of size $E$ makes RMSE at least $E/\sqrt n$, however many perfect forecasts surround it.
  • Non-additivity: the RMSE of the whole sample is not the mean of the RMSEs of its parts. Squares add up: $\mathrm{RMSE}^2=\sum_g \tfrac{n_g}{n}\,\mathrm{RMSE}_g^2$.
  • It is a norm (up to the factor $1/\sqrt n$): for error vectors $a$ and $b$ the triangle inequality holds, $\mathrm{RMSE}(a+b)\le\mathrm{RMSE}(a)+\mathrm{RMSE}(b)$.

Bias and spread: Pythagoras for errors

The residuals split into a systematic part — the mean $\bar r$ (the model over- or under-estimates on average) — and a random part, the spread around the mean $\sigma_r$. Then

$$\mathrm{RMSE}^2=\underbrace{\bar r^{\,2}}_{\text{bias}^2}+\underbrace{\sigma_r^2}_{\text{residual variance}},\qquad \bar r=\frac1n\sum_i r_i,\quad \sigma_r^2=\frac1n\sum_i\bigl(r_i-\bar r\bigr)^2$$
Deriving the decomposition

Write $r_i=\bar r+(r_i-\bar r)$ and expand the square:

$$\frac1n\sum_i r_i^2=\frac1n\sum_i\Bigl(\bar r^{\,2}+2\bar r\,(r_i-\bar r)+(r_i-\bar r)^2\Bigr)=\bar r^{\,2}+\frac{2\bar r}{n}\underbrace{\sum_i(r_i-\bar r)}_{=\,0}+\sigma_r^2$$

The middle term vanishes: deviations from the mean sum to zero. It is the same algebra as in $\operatorname{Var}X=\mathbb E X^2-(\mathbb E X)^2$.

Figure 2. On the left, 40 residuals with bias $\bar r$ and spread $\sigma_r$; on the right, a right triangle with legs $|\bar r|$ and $\sigma_r$ — its hypotenuse is RMSE. With $\bar r=1$ and $\sigma_r=1.5$ we get $\mathrm{RMSE}=\sqrt{1+2.25}\approx1.80$.

In the running example $\bar r=-0.5$ (the model over-estimates by $0.5$ on average), $\sigma_r\approx1.080$, and $0.25+1.167=1.417=\mathrm{MSE}$. The practical takeaway: bias can be removed for free — add $\bar r$ to every forecast, and on the data where it was estimated RMSE drops exactly to $\sigma_r$ (here from $1.190$ to $1.080$). In practice $\bar r$ is estimated on validation data and the gain is checked on the test set.

RMSE and the standard deviation

If the mean residual is zero (which is always the case for linear regression with an intercept on its training data), RMSE equals the standard deviation of the residuals. Hence its kinship with the “standard error of the regression” in statistics — except that there the sum of squared residuals is divided not by $n$ but by the degrees of freedom $n-p$ ($p$ is the number of model parameters). If, in addition, the errors are normal, about $68\%$ of the residuals lie within $\pm\mathrm{RMSE}$ and about $95\%$ within $\pm2\,\mathrm{RMSE}$.

RMSE versus MAE: what the gap says

MAE answers “how far off are we on average”, RMSE answers “how large is a typical error, counting the big ones”. Their ratio $\mathrm{RMSE}/\mathrm{MAE}$ is dimensionless and scale-free: it describes only the shape of the error distribution.

ErrorsMAERMSERMSE / MAE
uniform on $[-a,\,a]$$a/2$$a/\sqrt3$$2/\sqrt3\approx1.155$
normal $N(0,\,\sigma^2)$$\sigma\sqrt{2/\pi}$$\sigma$$\sqrt{\pi/2}\approx1.253$
Laplace with scale $b$$b$$\sqrt2\,b$$\sqrt2\approx1.414$
all $|r_i|$ equal $c$$c$$c$$1$
one error $E$, the other $n-1$ are zero$E/n$$E/\sqrt n$$\sqrt n$
Where √(π/2) comes from for normal errors

For $r\sim N(0,\sigma^2)$ we have $\mathbb E\,r^2=\sigma^2$, and the mean absolute value is twice the integral over the positive half-line:

$$\mathbb E|r|=2\int_0^\infty \frac{x}{\sigma\sqrt{2\pi}}\,e^{-x^2/2\sigma^2}\,dx=\frac{2\sigma^2}{\sigma\sqrt{2\pi}}=\sigma\sqrt{\frac{2}{\pi}}$$

Hence $\sigma/\bigl(\sigma\sqrt{2/\pi}\bigr)=\sqrt{\pi/2}\approx1.2533$. On a finite sample it holds approximately: in Figure 3 with $n=2000$ we get $1.248$.

Figure 3. 2000 errors with unit variance (fixed generator seed). For normal errors the ratio is $1.248$ (theory $1.253$), for Laplace errors $1.392$ ($1.414$), for uniform ones $1.153$ ($1.155$). Add outliers: each error is multiplied by 10 with probability $\varepsilon$. Already at $\varepsilon=5\%$ RMSE jumps from $1.009$ to $2.817$, while MAE only moves from $0.809$ to $1.258$.

For such a mixture MSE grows $1+99\varepsilon$ times ($(1-\varepsilon)\cdot1+\varepsilon\cdot100$) while MAE grows only $1+9\varepsilon$ times, so the theoretical ratio is $\sqrt{1+99\varepsilon}\,/\bigl((1+9\varepsilon)\,\mathrm{MAE}_0\bigr)$, where $\mathrm{MAE}_0$ is the MAE of the original distribution.

The bounds: MAE ≤ RMSE ≤ √n · MAE

$$\mathrm{MAE}\;\le\;\mathrm{RMSE}\;\le\;\sqrt n\;\mathrm{MAE}$$

The left equality holds only when all $|r_i|$ are equal; the right one when the whole error sits in a single object and all other forecasts are perfect. In the running example the ratio is $1.190/0.833\approx1.43$ against the maximum $\sqrt3\approx1.73$: the errors are clearly uneven.

Proof of both bounds

The left bound is the Cauchy–Schwarz inequality for the vectors $(|r_1|,\dots,|r_n|)$ and $(1,\dots,1)$:

$$\sum_i|r_i|\cdot1\le\sqrt{\sum_i r_i^2}\cdot\sqrt n\quad\Longrightarrow\quad\frac1n\sum_i|r_i|\le\sqrt{\frac1n\sum_i r_i^2}$$

Equality holds when the vectors are proportional, i.e. all $|r_i|$ are equal. The right bound follows from the fact that the sum of squares of non-negative numbers does not exceed the square of their sum:

$$\sum_i r_i^2\le\Bigl(\sum_i|r_i|\Bigr)^2\quad\Longrightarrow\quad\sqrt{\frac1n\sum_i r_i^2}\le\frac{1}{\sqrt n}\sum_i|r_i|=\sqrt n\,\mathrm{MAE}$$

Equality holds when all products $|r_i|\,|r_j|$ with $i\ne j$ are zero, i.e. there is at most one non-zero error. If the total absolute error is split equally among $k$ of the $n$ objects, the ratio is exactly $\sqrt{n/k}$.

Figure 4. On the left, two errors $(r_1,\,r_2)$. Points with the same MAE lie on the diamond $|r_1|+|r_2|=2\,\mathrm{MAE}$, points with the same RMSE on the circle of radius $\sqrt2\,\mathrm{RMSE}$. The diamond is squeezed between the circles $\mathrm{RMSE}=\mathrm{MAE}$ (touching it where $|r_1|=|r_2|$) and $\mathrm{RMSE}=\sqrt2\,\mathrm{MAE}$ (through the vertices on the axes). For the point $(0.5,\,-2)$: $\mathrm{MAE}=1.25$, $\mathrm{RMSE}\approx1.458$. On the right, the ratio $\sqrt{n/k}$ when the error is split equally among $k$ of the $n$ objects.
How to read the gap

$\mathrm{RMSE}\approx\mathrm{MAE}$ — the errors are of about the same size. $\mathrm{RMSE}/\mathrm{MAE}\approx1.25$ — typical of normal noise. Clearly above $1.4$ — heavy tails or a few large misses: look at the largest residuals before trusting the averages.

Geometry: RMSE as a distance

Write the actuals and the forecasts as points of $n$-dimensional space: $y=(y_1,\dots,y_n)$ and $\hat y=(\hat y_1,\dots,\hat y_n)$. The sum of squared errors is the square of the ordinary Euclidean distance between them, so

$$\mathrm{RMSE}(y,\hat y)=\frac{\|y-\hat y\|_2}{\sqrt n}$$

Dividing by $\sqrt n$ makes the distance comparable across sample sizes: if every error equals $c$, then $\|y-\hat y\|=c\sqrt n$ and RMSE is exactly $c$. All forecasts with the same RMSE form a sphere of radius $\sqrt n\,\mathrm{RMSE}$ centred at $y$. With $n=3$ we can draw it.

Figure 5. The running example in $\mathbb R^3$: actual $y=(3,\,5,\,8)$, forecast $\hat y=(2.5,\,5,\,10)$; the orange segment is the error vector of length $\sqrt{4.25}\approx2.062$, and $\mathrm{RMSE}=2.062/\sqrt3\approx1.190$. The grey sphere holds all forecasts with the same RMSE. The dashed diagonal holds the constant forecasts $(c,\,c,\,c)$; its point closest to $y$ is $\bar y\cdot\mathbf 1$, $\bar y=16/3$. Move the sliders and rotate the scene.

The best constant is the mean, and its RMSE is the standard deviation

Which constant forecast $\hat y_i=c$ minimises RMSE? Geometrically it is the orthogonal projection of $y$ onto the diagonal, i.e. $c=\bar y$. Its RMSE is the standard deviation of the target:

$$\min_c\,\mathrm{RMSE}(y,\,c\mathbf 1)=\mathrm{RMSE}(y,\,\bar y\mathbf 1)=\sqrt{\frac1n\sum_i\bigl(y_i-\bar y\bigr)^2}=\sigma_y$$

This is the main reference point for reading RMSE: a model whose RMSE is not below $\sigma_y$ is no better than “always predict the mean”. In the example $\sigma_y\approx2.055$, and the model achieves $1.190$. The coefficient of determination follows from the same picture:

$$R^2=1-\frac{\mathrm{MSE}}{\sigma_y^2}=1-\frac{\mathrm{RMSE}^2}{\sigma_y^2}=1-\frac{1.417}{4.222}\approx0.66$$

Derivative and gradient

Let the forecasts depend on model parameters $\theta$. The derivative of $\sqrt u$ is $1/(2\sqrt u)$, so by the chain rule the gradient of RMSE is the gradient of MSE divided by $2\,\mathrm{RMSE}$:

$$\nabla_\theta\,\mathrm{RMSE}=\frac{\nabla_\theta\,\mathrm{MSE}}{2\,\mathrm{RMSE}}$$
Step-by-step derivation

Differentiate with respect to one forecast $\hat y_j$. Only the term $(y_j-\hat y_j)^2$ depends on it:

$$\frac{\partial\,\mathrm{MSE}}{\partial\hat y_j}=\frac1n\cdot2\,(y_j-\hat y_j)\cdot(-1)=-\frac{2}{n}\,r_j$$

The chain rule for $\mathrm{RMSE}=\sqrt{\mathrm{MSE}}$:

$$\frac{\partial\,\mathrm{RMSE}}{\partial\hat y_j}=\frac{1}{2\sqrt{\mathrm{MSE}}}\cdot\Bigl(-\frac{2}{n}\,r_j\Bigr)=-\frac{r_j}{n\,\mathrm{RMSE}}=\frac{\hat y_j-y_j}{n\,\mathrm{RMSE}}$$

For a parameter $\theta$ one more chain-rule factor appears, $\partial\hat y_j/\partial\theta$:

$$\frac{\partial\,\mathrm{RMSE}}{\partial\theta}=\frac{1}{n\,\mathrm{RMSE}}\sum_{j=1}^{n}(\hat y_j-y_j)\,\frac{\partial\hat y_j}{\partial\theta}$$
$$\frac{\partial\,\mathrm{RMSE}}{\partial\hat y_j}=\frac{\hat y_j-y_j}{n\,\mathrm{RMSE}}$$

What follows from this:

  • Same direction, different length. The gradients of RMSE and MSE differ only by the positive factor $1/(2\,\mathrm{RMSE})$. Hence the two functions share their stationary points and their minimum.
  • The gradient with respect to the forecasts has constant length: $\|\nabla_{\hat y}\mathrm{RMSE}\|=1/\sqrt n$ for any errors (the sum of the squared components is $\sum_j r_j^2/(n^2\,\mathrm{MSE})=1/n$). The RMSE gradient points only in the direction of $y$, and its length does not depend on how far away we are.
  • In the running example $\partial\,\mathrm{RMSE}/\partial\hat y=(-0.140,\;0,\;0.560)$, while for MSE it is $(-0.333,\;0,\;1.333)$, exactly $2\cdot1.190=2.380$ times larger.
  • There is no derivative at zero. At $\hat y=y$ the function $\|y-\hat y\|/\sqrt n$ has a kink, like $|x|$ at zero (the tip of a cone), and the formula divides by $\mathrm{RMSE}=0$. In automatic differentiation this turns into NaN (see the code section).

A one-dimensional slice: the constant forecast

Take the constant model $\hat y_i=c$ on the example data $y=(3,\,5,\,8)$. Then $\mathrm{MSE}(c)=(c-\bar y)^2+\sigma_y^2$ is a parabola and RMSE is a hyperbola:

$$\mathrm{RMSE}(c)=\sqrt{(c-\bar y)^2+\sigma_y^2},\qquad \mathrm{RMSE}'(c)=\frac{c-\bar y}{\sqrt{(c-\bar y)^2+\sigma_y^2}}\in(-1,\,1)$$

Near the minimum the hyperbola looks like a parabola (RMSE behaves like MSE), far away like the lines $|c-\bar y|$ (like MAE). The derivative moves smoothly from $-1$ to $1$ and never leaves these bounds, whereas the derivative of MSE grows linearly without bound.

Figure 6. Top: RMSE, MSE and MAE of the constant forecast $c$ (the points on the axis are the data); bottom: the derivatives. At $c=8$: $\mathrm{RMSE}\approx3.367$, $\mathrm{RMSE}'\approx0.792$, $\mathrm{MSE}'\approx5.333$; their ratio is $2\,\mathrm{RMSE}\approx6.733$. The minima of RMSE and MSE are at $\bar y\approx5.333$, the minimum of MAE at the median 5.

The second derivative $\mathrm{RMSE}''(c)=\sigma_y^2/\mathrm{RMSE}(c)^3>0$: the function is strictly convex as long as $\sigma_y>0$. In general RMSE is convex in the forecasts (as a norm), and therefore in the parameters of a linear model: linear regression has no local minima for either MSE or RMSE.

The RMSE(w, b) landscape and training

A linear model $\hat y=wx+b$ on 14 points. Over the parameter plane $(w,\,b)$ RMSE forms a bowl. Switch the surface to MSE: the level lines stay the same (the level $\mathrm{RMSE}=1.5$ is the level $\mathrm{MSE}=2.25$), only the height changes: MSE grows quadratically, while far from the minimum RMSE grows almost linearly, like a cone.

Figure 7. Left: the surface (rotatable); right: the top view with RMSE level lines; bottom: RMSE by step. Drag the black starting point: the arrows show the first step $-\eta\nabla$ for MSE (blue) and for RMSE (orange) — same direction, but the orange one is $2\,\mathrm{RMSE}\approx5.4$ times shorter. Press “Play”: with $\eta=0.1$ descent on MSE gets within $0.01$ of the minimum $0.904$ in 61 steps, descent on RMSE in 140. Set $\eta=0.14$: descent on MSE diverges, while descent on RMSE reaches the target in 100 steps.

Why. A step on RMSE is a step on MSE with a variable learning rate:

$$\theta\leftarrow\theta-\eta\,\nabla\mathrm{RMSE}=\theta-\underbrace{\frac{\eta}{2\,\mathrm{RMSE}(\theta)}}_{\eta_{\text{eff}}}\,\nabla\mathrm{MSE}$$

While the errors are large the effective step is small — which is why descent on RMSE tolerates a too-large $\eta$ better. Near the minimum $\eta_{\text{eff}}\to\eta/(2\,\mathrm{RMSE}_{\min})$; here $\mathrm{RMSE}_{\min}\approx0.904$, and the step is almost half that of MSE — hence the slow finish. Descent on MSE is stable only for $\eta<2/\lambda_{\max}\approx0.133$, where $\lambda_{\max}\approx15.0$ is the largest eigenvalue of the Hessian of MSE.

RMSE on mini-batches

The root of a batch mean is not the root of the full-sample mean: $\mathbb E\sqrt{\mathrm{MSE}_{\text{batch}}}\le\sqrt{\mathbb E\,\mathrm{MSE}_{\text{batch}}}$ (Jensen’s inequality). The batch-averaged RMSE is systematically too low, and SGD steps on batch RMSE optimise exactly that average rather than the RMSE of the whole sample. Usually one trains on MSE and computes RMSE over the whole validation set.

RMSE in model evaluation

As a quality metric RMSE answers “by how many units of $y$ is the model typically off, with emphasis on big misses”. For the number to mean something, compare it:

  • with a baseline — the “always the mean” forecast has RMSE $\sigma_y$, the “same as yesterday” forecast of a time series has its own; the model should be clearly better;
  • with the scale of the task — an error of 5000 is great for flats and awful for cups of coffee. The dimensionless version is $\mathrm{NRMSE}=\mathrm{RMSE}/\sigma_y=\sqrt{1-R^2}$ (sometimes one divides by the range or the mean of $y$);
  • with MAE — the ratio $\mathrm{RMSE}/\mathrm{MAE}$ shows whether there are large misses;
  • only on the same data — RMSEs on different test sets are not comparable if their $y$ spreads differ.

Cross-validation: average the squares

With $K$ folds people often take the mean of the fold RMSEs. That is not the RMSE over all objects: the mean of roots is at most the root of the mean. The overall estimate is the root of the weighted mean MSE:

$$\mathrm{RMSE}_{\text{CV}}=\sqrt{\sum_{k=1}^{K}\frac{n_k}{n}\,\mathrm{MSE}_k}\;\ge\;\sum_{k=1}^{K}\frac{n_k}{n}\,\mathrm{RMSE}_k$$

For example, two folds of equal size with RMSE $1$ and $3$: the mean is $2$, while the overall RMSE is $\sqrt{(1+9)/2}=\sqrt5\approx2.24$.

The Netflix Prize

In 2006 Netflix promised a million dollars to the team that would improve the RMSE of its Cinematch recommender on the test ratings by $10\%$ — from $0.9525$ to $0.8572$ on the five-star scale. In 2009 the prize went to BellKor’s Pragmatic Chaos with RMSE $0.8567$. For a tenth of a “star” of RMSE the participants spent three years building ensembles of hundreds of models — a good illustration that the metric determines what exactly gets optimised.

Variants: RMSLE, weighted and normalised RMSE

RMSLE (root mean squared logarithmic error) is RMSE on a log scale:

$$\mathrm{RMSLE}=\sqrt{\frac1n\sum_{i=1}^{n}\bigl(\ln(1+\hat y_i)-\ln(1+y_i)\bigr)^2}$$

The logarithm turns ratios into differences: the error is determined by how many times $1+\hat y$ differs from $1+y$, not by how much. That is why RMSLE suits non-negative targets that span many scales (prices, sales, views) and punishes an under-forecast harder than an over-forecast of the same absolute size. In the running example $\mathrm{RMSLE}\approx0.139$.

Figure 8. The squared log error for an actual $y=10$. A forecast of 5 (5 too low) costs $0.367$, a forecast of 15 (the same 5 too high) costs $0.140$, $2.6$ times less. The dashed curve is the mirror image, the dotted one the squared error in units of $1+y$ for comparison. Bottom: the derivative with respect to $\hat y$ — steeper on the low side.

Two more useful modifications:

  • weighted RMSE $\sqrt{\sum_i w_i r_i^2/\sum_i w_i}$ — when objects are not equally important (expensive goods, recent observations);
  • NRMSE $=\mathrm{RMSE}/\sigma_y=\sqrt{1-R^2}$ — a dimensionless version for comparing tasks of different scales.
RMSLE is RMSE on logarithms

RMSLE equals the RMSE between $\ln(1+y)$ and $\ln(1+\hat y)$. So if a competition is scored by RMSLE, it makes sense to train with MSE on the target $\ln(1+y)$ and return forecasts via $e^{z}-1$.

In code

In NumPy RMSE is one line; below we also check the formulas of this page on the running example.

pythonimport numpy as np

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

r    = y - y_hat                   # residuals: [ 0.5  0.  -2. ]
mse  = np.mean(r ** 2)             # ≈ 1.4167
rmse = np.sqrt(mse)                # ≈ 1.1902
mae  = np.mean(np.abs(r))          # ≈ 0.8333

# The same via the Euclidean norm: ‖y − ŷ‖ / √n
print(round(np.linalg.norm(r) / np.sqrt(len(r)), 4))   # 1.1902

# Decomposition: RMSE² = bias² + residual variance
print(round(r.mean() ** 2 + r.var(), 4), round(mse, 4))   # 1.4167 1.4167

# Gradient with respect to the forecasts: ∂RMSE/∂ŷ = (ŷ − y) / (n · RMSE)
print(np.round((y_hat - y) / (len(y) * rmse), 4))       # [-0.14    0.      0.5601]

# The “always the mean” baseline: its RMSE is the standard deviation of y
print(round(np.std(y), 4))                               # 2.0548

scikit-learn has ready-made functions (since version 1.4; before that one wrote mean_squared_error(..., squared=False); the squared parameter was removed in 1.6). Note the difference between the mean fold RMSE and the RMSE over all objects:

pythonfrom sklearn.metrics import root_mean_squared_error, root_mean_squared_log_error
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold, cross_val_score, cross_val_predict

# y, y_hat come from the listing above; the functions exist in scikit-learn ≥ 1.4
print(round(root_mean_squared_error(y, y_hat), 4))       # 1.1902
print(round(root_mean_squared_log_error(y, y_hat), 4))   # 0.1392 — RMSLE

X, t = make_regression(n_samples=200, n_features=5, noise=10.0, random_state=0)
cv = KFold(5, shuffle=True, random_state=0)
# scorers are “higher is better”, so RMSE comes with a minus sign
scores = cross_val_score(LinearRegression(), X, t, cv=cv,
                         scoring="neg_root_mean_squared_error")
print(round(-scores.mean(), 3))                # 10.56 — mean RMSE of the folds
pred = cross_val_predict(LinearRegression(), X, t, cv=cv)
print(round(root_mean_squared_error(t, pred), 3))   # 10.614 — RMSE over all objects

In PyTorch RMSE as a loss needs care at zero:

pythonimport torch

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

rmse = torch.sqrt(torch.mean((y_hat - y) ** 2))
rmse.backward()
print(round(rmse.item(), 4), y_hat.grad)   # 1.1902 tensor([-0.1400,  0.0000,  0.5601])

# A perfect forecast: the derivative of √u at zero is infinite → NaN gradient
p = y.clone().requires_grad_(True)
torch.sqrt(torch.mean((p - y) ** 2)).backward()
print(p.grad)                    # tensor([nan, nan, nan])

def rmse_loss(pred, target, eps=1e-8):
    """RMSE as a loss: eps under the root removes the NaN."""
    return torch.sqrt(torch.mean((pred - target) ** 2) + eps)
Rule of thumb

To train a neural network one usually minimises MSE: the same minimum, a gradient that is smooth at zero, no division by RMSE. RMSE is computed for the report — over the whole validation set at once, not as a mean over batches.

Common mistakes

  1. The mean RMSE over batches or folds as the final RMSE. The root is non-linear: average MSE and take the root at the end.
  2. Comparing RMSE across different data. RMSE depends on the scale and spread of $y$; compare models on the same test set or use a normalised RMSE.
  3. “The model is off by RMSE on average”. The mean absolute error is MAE; RMSE is never smaller, and with heavy tails it is noticeably larger.
  4. RMSE as a loss without protecting zero. The derivative of $\sqrt u$ at zero is infinite: a perfect batch gives NaN gradients. Add $\varepsilon$ under the root or train on MSE.
  5. Ignoring outliers. One error of 100 units among 99 perfect forecasts gives $\mathrm{RMSE}=10$ with $\mathrm{MAE}=1$. If outliers are noise rather than important events, look at MAE, Huber or error quantiles.
  6. RMSE on logarithms instead of the original scale. If the model is trained on $\ln(1+y)$, its RMSE is the RMSLE of the original task, not the RMSE in dollars; transform the forecasts back before computing RMSE.
  • MSE: $\mathrm{RMSE}=\sqrt{\mathrm{MSE}}$ — the same minimum and the same ranking of models, while the gradient is divided by $2\,\mathrm{RMSE}$.
  • MAE: $\mathrm{MAE}\le\mathrm{RMSE}\le\sqrt n\,\mathrm{MAE}$; the best constant for MAE is the median, for RMSE the mean.
  • Huber: quadratic near zero and linear in the tails — a compromise between MSE (and hence RMSE) and MAE.
  • MAPE: a relative error instead of an absolute one; RMSLE is its quadratic relative on a log scale.
  • SGD: descent on RMSE is descent on MSE with learning rate $\eta/(2\,\mathrm{RMSE})$.
  • Adam: divides the step by the root of a running mean of squared gradients — the same “root mean square” (RMS) idea as in RMSE.

Summary

1) $\mathrm{RMSE}=\sqrt{\mathrm{MSE}}$ is the typical size of an error in the units of $y$ with emphasis on big misses. 2) $\mathrm{MAE}\le\mathrm{RMSE}\le\sqrt n\,\mathrm{MAE}$; the ratio RMSE/MAE is a tail indicator ($\approx1.25$ for normal noise). 3) $\mathrm{RMSE}^2=\bar r^{\,2}+\sigma_r^2$ — bias and spread as the legs of a triangle. 4) Geometrically it is the distance $\|y-\hat y\|/\sqrt n$; the best constant is the mean, with RMSE equal to $\sigma_y$. 5) $\nabla\mathrm{RMSE}=\nabla\mathrm{MSE}/(2\,\mathrm{RMSE})$: a shared minimum, a different step, no derivative at zero.

Check yourself

1. The model’s errors are $(1,\,-1,\,1,\,-1)$. What are MAE and RMSE?
2. Out of 100 objects 99 forecasts are perfect and one is off by 50. What is RMSE?
3. The mean residual is $\bar r=3$ and the standard deviation of the residuals is $\sigma_r=4$. What is RMSE?
4. How are the gradients of RMSE and MSE with respect to the parameters related?
5. Five folds of equal size gave RMSE $1$, $1$, $1$, $1$ and $3$. What is the RMSE over all objects?