Sub topic 3
MSE and RMSE: squaring errors, then returning to original units
This chapter assumes you can read basic NumPy code and know what a residual is. A residual is the prediction minus the true value, covered in the first chapter. It also assumes you have seen MAE, the mean of the absolute residuals. Here you will build Mean Squared Error (MSE) and Root Mean Squared Error (RMSE) from residuals, see what units each one has, and learn the mistakes that most often corrupt them in practice.
The definitions
MSE is the mean of the squared residuals. With n predictions, true values y_i and predictions ŷ_i:
- Residual:
e_i = ŷ_i - y_i - MSE:
(1/n) * Σ e_i² - RMSE:
sqrt(MSE)
Squaring does two things. It makes every term non-negative, so positive and negative misses cannot cancel each other. It also makes large misses count much more than small ones. A miss of 3 contributes 9, while a miss of 0.5 contributes 0.25.
The square root at the end undoes the unit change. If the target is measured in dollars, residuals are in dollars and squared residuals are in dollars squared. Dollars squared have no direct meaning. RMSE is back in dollars, so you can compare it with the target and with MAE.
| Quantity | Formula | Units when the target is in dollars |
|---|---|---|
| Residual | `ŷ - y` | dollars |
| MAE | mean of `abs(e)` | dollars |
| MSE | mean of `e²` | dollars squared |
| RMSE | `sqrt(MSE)` | dollars |
A worked example by hand
Use the same four points as before. The true values are [3.0, 5.0, 2.5, 7.0] and the predictions are [2.5, 5.0, 4.0, 8.0].
- Residuals:
[-0.5, 0.0, 1.5, 1.0] - Squared residuals:
[0.25, 0.0, 2.25, 1.0] - Sum of squares:
3.5 - MSE:
3.5 / 4 = 0.875 - RMSE:
sqrt(0.875) ≈ 0.9354
For comparison, MAE on the same data is 0.75. Suppose the target is a price in thousands of dollars. Then MAE is 0.75 thousand dollars, RMSE is about 0.94 thousand dollars, and MSE is 0.875 thousand-dollars squared. Only the first two can be read as "typical miss" figures.
The same steps as reusable functions:
import numpy as np
def mse(y_true, y_pred):
y_true = np.asarray(y_true, dtype=float)
y_pred = np.asarray(y_pred, dtype=float)
if y_true.shape != y_pred.shape:
raise ValueError(f"shape mismatch: {y_true.shape} vs {y_pred.shape}")
return float(np.mean((y_pred - y_true) ** 2))
def rmse(y_true, y_pred):
return float(np.sqrt(mse(y_true, y_pred)))
y_true = [3.0, 5.0, 2.5, 7.0]
y_pred = [2.5, 5.0, 4.0, 8.0]
print(f"MSE = {mse(y_true, y_pred):.4f}") # 0.8750
print(f"RMSE = {rmse(y_true, y_pred):.4f}") # 0.9354The shape check matters. If one array has shape (4,) and the other (4, 1), NumPy broadcasts the subtraction into a 4×4 grid and np.mean returns a plausible but wrong number with no error. This is a very common source of silently incorrect MSE values, especially when a model returns column vectors.
How RMSE relates to MAE
RMSE is never smaller than MAE on the same residuals. It is also bounded above:
MAE ≤ RMSE ≤ sqrt(n) * MAE
The lower bound is equality when every residual has the same absolute size. The upper bound is equality when all the error sits in a single point. You can check both with four residuals whose absolute values sum to 4:
import numpy as np
spread_evenly = np.array([1.0, 1.0, 1.0, 1.0])
one_big_miss = np.array([0.0, 0.0, 0.0, 4.0])
for errors in (spread_evenly, one_big_miss):
mae = np.mean(np.abs(errors))
rmse = np.sqrt(np.mean(errors ** 2))
print(mae, rmse)
# Both have MAE 1.0. RMSE is 1.0 for the first and 2.0 for the second,
# which is sqrt(4) * 1.0, the upper bound for n = 4.The gap between RMSE and MAE therefore tells you something about the shape of your errors. A ratio near 1 means the errors are similar in size. A larger ratio means a few big misses dominate. The next chapter treats this in detail, so here it serves as a diagnostic: always compute both and look at the ratio.
Why squared error is the default
MAE is easier to read, so it is fair to ask why MSE is used so widely. There are three practical reasons.
- Smooth to optimize. The squared term has a derivative everywhere, so gradient-based training and closed-form solutions work cleanly. The absolute value has a kink at zero.
- Ordinary least squares minimizes it.
LinearRegressionin scikit-learn chooses coefficients that minimize the sum of squared residuals. Reporting MSE or RMSE on the training objective keeps the metric aligned with what the model optimized. - Link to the mean. The single constant that minimizes MSE is the mean of the target. The constant that minimizes MAE is the median. This is why the predict-the-mean baseline in a later chapter pairs naturally with squared error.
You can verify the last point numerically:
import numpy as np
y = np.array([3.0, 5.0, 2.5, 7.0])
for name, c in (("mean", y.mean()), ("median", np.median(y))):
print(name, c, np.mean((y - c) ** 2))
# mean 4.375 3.171875
# median 4.0 3.3125The mean gives the lower MSE. If you tried any other constant, including values like 4.4 or 4.3, the MSE would be higher than 3.171875.
Computing MSE and RMSE with scikit-learn
mean_squared_error returns MSE. To get RMSE, take the square root yourself:
import numpy as np
from sklearn.metrics import mean_squared_error
y_true = [3.0, 5.0, 2.5, 7.0]
y_pred = [2.5, 5.0, 4.0, 8.0]
mse_value = mean_squared_error(y_true, y_pred)
rmse_value = np.sqrt(mse_value)
print(f"MSE={mse_value:.4f} RMSE={rmse_value:.4f}")
# MSE=0.8750 RMSE=0.9354The functions take (y_true, y_pred) in that order. MSE is symmetric, so swapping the arguments gives the same value. That is not true of r2_score, so building the habit of passing true values first avoids bugs later.
For multi-output regression, mean_squared_error averages over outputs by default (multioutput="uniform_average"). Pass multioutput="raw_values" to get one MSE per output. If the outputs have different units, a single averaged number mixes incompatible scales, so look at the per-output values.
Common errors
Reporting MSE as if it were in target units
An MSE of 25 on a target measured in meters is 25 square meters. Say "RMSE of 5 meters" instead. If a report quotes MSE, state the squared unit or switch to RMSE.
Taking the root in the wrong place
RMSE is the square root of the mean of squares. It is not the mean of the square roots. The mean of the square roots of the squared residuals is just MAE, because sqrt(e²) = |e|. Writing np.mean(np.sqrt(e ** 2)) therefore returns MAE, which is a valid metric but not the one you intended.
Averaging RMSE across cross-validation folds
Suppose two folds of equal size have MSE values 4 and 16. Averaging the fold RMSE values and taking the root of the averaged MSE give different answers:
import numpy as np
fold_mse = np.array([4.0, 16.0])
print(np.mean(np.sqrt(fold_mse))) # 3.0
print(np.sqrt(np.mean(fold_mse))) # 3.1622776601683795The second number is the RMSE you would get by pooling all the residuals together, so it equals the RMSE of one big evaluation. The first is always less than or equal to the second. Pick one convention, state it, and use it for every model you compare. If folds differ in size, weight by fold size when averaging MSE.
Comparing RMSE across different targets
RMSE carries the scale of the target. An RMSE of 12 is excellent for house prices in thousands of dollars and terrible for a target that ranges from 0 to 1. Compare RMSE only between models on the same target and the same evaluation data. To judge an RMSE alone, compare it with the standard deviation of the target (which is the RMSE of the predict-the-mean baseline) or with the target's typical range.
Reading RMSE after transforming the target
If you train on log(y) and compute RMSE on the log scale, the number describes log units, not the original units. Convert predictions back with exp before computing RMSE if stakeholders care about errors in the original scale. Be aware that the back-transformed predictions are biased toward the median, which changes the result.
Evaluating on training data
RMSE on the training set measures how well the model memorized the data it saw. It is nearly always lower than RMSE on new data. Use a held-out test split, as in the example below, for any number you report.
A full example on held-out data
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error
from sklearn.model_selection import train_test_split
X, y = make_regression(n_samples=200, n_features=3, noise=10.0, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_test)
mae = mean_absolute_error(y_test, pred)
mse = mean_squared_error(y_test, pred)
rmse = np.sqrt(mse)
print(f"MAE : {mae:.2f}")
print(f"RMSE : {rmse:.2f}")
print(f"RMSE/MAE ratio: {rmse / mae:.2f}")
print(f"Target std : {y_test.std():.2f}")Two comparisons make the output readable. The RMSE/MAE ratio shows how uneven the errors are. For roughly bell-shaped errors, the ratio tends to land near 1.25. The target's standard deviation is the RMSE you would get by always predicting the test-set mean, so an RMSE well below it means the model adds information. The exact printed values depend on your library versions, so run the script rather than relying on remembered numbers. Because the noise level is set to 10, the RMSE should land near 10.
Quick reference
- MSE penalizes big misses heavily and is in squared units. Use it for optimization and for analysis that depends on variance.
- RMSE is in target units, which makes it the form you report. It is always at least MAE.
- Check shapes before subtracting, since broadcasting can hide bugs.
- Pool residuals, or average MSE, before taking the root when summarizing folds.
- Compare RMSE only on the same target and the same data.
Exercise
A model predicts [12, 18, 33] for the true values [10, 20, 30]. Compute the MSE and the RMSE by hand, give the unit of each if the target is in kilograms, and say whether the RMSE is larger or smaller than the MAE.
Show answer
Residuals are [2, -2, 3]. Squared residuals are [4, 4, 9], which sum to 17. MSE = 17 / 3 ≈ 5.667 kg². RMSE = sqrt(5.667) ≈ 2.38 kg. The MAE is (2 + 2 + 3) / 3 ≈ 2.33 kg, so the RMSE (2.38) is slightly larger, as it must be. The two are close because the three residuals have similar sizes.
Exercise
Two cross-validation folds of equal size have RMSE values 3 and 5. A teammate reports the overall RMSE as 4. What is the pooled RMSE, and why does it differ from 4?
Show answer
The MSE values are 9 and 25, so the mean MSE is 17 and the pooled RMSE is sqrt(17) ≈ 4.12. The teammate averaged the RMSE values, but the square root is not linear, so the mean of the roots (4) is smaller than the root of the mean (about 4.12). Large-error folds count more when you average squares first, which matches how the pooled residuals would behave.