What you will be able to do
- Compute MSE, RMSE and MAE from a set of residuals and say what units each one is in
- Pick between RMSE and MAE depending on whether a few large errors should dominate the score
- Interpret an R-squared value of 1, 0 or below 0 on a holdout set
- Recognise when MAPE, median absolute error, max error or MSLE/RMSLE is the right variant
- Tell which metrics are minimised and which are maximised, and why scikit-learn exposes errors as neg_* scorers
Key concept
Residual-based error metric — A regression metric takes the residual (true value minus prediction) for every row and collapses them into one number. How it treats each residual (squaring it, taking its absolute value, dividing it by the true value, or keeping only the worst one) decides which mistakes the metric cares about.
1.MSE, RMSE and MAE: squaring versus absolute value
A regression model outputs a number, so you judge it by how far that number lands from the truth. The gap on one row is the residual. Every error metric here averages those residuals in some way. They differ in what they do to each residual before averaging, and that choice decides which mistakes get punished.
Mean absolute error (MAE) takes the absolute value of each residual and averages them. Mean squared error (MSE) squares each residual and averages the squares. Root mean squared error (RMSE) is the square root of MSE. Taking the square root brings the number back to the units of the target. An RMSE of 3 on a delivery-time model means about 3 minutes or hours, whatever the target is measured in. MSE in that case would be in squared minutes.
>>> from sklearn.metrics import mean_absolute_error
>>> y_true = [3, -0.5, 2, 7]
>>> y_pred = [2.5, 0.0, 2, 8]
>>> mean_absolute_error(y_true, y_pred)
0.5Running mean_squared_error on the same four predictions returns 0.375. The squares are 0.25, 0.25, 0 and 1, and their mean is 0.375. The RMSE is the square root of that, about 0.61. In a Databricks notebook RMSE is often built exactly this way, as np.sqrt around mean_squared_error. In SparkR it is written by hand as the square root of the summed squared errors divided by the row count.
Squaring is what separates the two families. A residual of 20 counts as 20 in MAE but as 400 in MSE, so a few extreme rows can account for most of an RMSE. MAE weights every unit of error the same, so the same rows only shift it in proportion to their size. Squaring does not cancel or shrink large errors. It amplifies them. (Spotting and removing such rows before training is a separate step, covered under Outliers: standard-deviation bounds and 1.5×IQR fences.)
Neither behaviour is wrong in itself. Choose based on what a large miss costs you:
- Use MAE when rare extreme cases should not drive model selection. A delivery-time model shouldn't be ranked mostly by a handful of freak shipping delays.
- Use RMSE (or MSE) when one big miss really is worse than several small ones. One badly under-forecast repair bill can break a maintenance budget, so the metric should punish large errors more than in proportion to their size.
- Squared error is the scoring function that matches predicting the mean. Absolute error is the one that matches predicting the median. That is why the two can rank the same pair of models differently.
| Metric | Per-row treatment | Units | Effect of a few huge residuals |
|---|---|---|---|
| MAE (mean_absolute_error) | Absolute value, averaged | Same as target | Grows linearly with them |
| MSE (mean_squared_error) | Squared, averaged | Target units squared | Dominated by them |
| RMSE (root_mean_squared_error) | Square root of MSE | Same as target | Dominated by them |
| MedAE (median_absolute_error) | Median of absolute residuals | Same as target | Robust to outliers |
Checkpoint 1 of 8· Fill the gap
This Databricks notebook computes RMSE from a regression model's test predictions. Which function completes the first line?
rmse = np. ? (mean_squared_error(y_test_reg, reg_pred))
r2 = r2_score(y_test_reg, reg_pred)RMSE is the square root of MSE. Taking the root puts the error back in the target's own units. Squaring MSE again or taking its absolute value gives a different quantity, not RMSE.
Source: docs.databricks.comCheckpoint 2 of 8· Check yourself
A delivery-time dataset has a few freak shipping delays with very large residuals. Which metric is least affected by those few extreme rows?
Squaring makes large residuals bigger, so MSE and RMSE are dominated by them. MAE still grows in proportion to them. The median of the absolute residuals barely moves when a few rows are extreme, which makes it the outlier-robust metric.
“The median_absolute_error is particularly interesting because it is robust to outliers.”Source: scikit-learn.org
Checkpoint 3 of 8· Exam question
A team runs a Databricks AutoML regression experiment to forecast equipment repair costs. Large under-predictions are especially costly because they cause the maintenance budget to be badly exceeded, so the team wants the leaderboard's primary metric to penalize large errors more heavily than small ones. Which metric should they configure AutoML to optimize?
Correct answer: A — Root mean squared error, because squaring each residual before averaging gives disproportionately more weight to large prediction misses than to small ones
- A. Because residuals are squared before being averaged, a repair-cost prediction that misses by a large margin contributes far more to root mean squared error than several small misses, matching the team's goal of penalizing big errors more heavily.
- B. Mean absolute error weights every residual linearly by its magnitude, so a large miss and several small misses of the same total size contribute equally, which does not emphasize large errors the way the team wants.
- C. A higher R-squared reflects more explained variance overall but does not specifically penalize large individual residuals more than small ones, so it is not the right lever for this requirement.
- D. Explained variance summarizes how much of the target's spread the model accounts for but, like R-squared, does not weight large individual residuals more heavily than small ones.
2.R-squared: error relative to predicting the mean
R² (the coefficient of determination) compares your model with the dumbest sensible baseline: always predicting the average of y. It measures the share of the target's variance that the model explains. MAE and RMSE are in the target's units. R² has no units, which is why it is the default ranking metric for AutoML regression and the default score for scikit-learn regressors.
R² is computed as 1 minus the model's sum of squared residuals divided by the sum of squared deviations of y from its mean. That formula gives three reference points:
- 1.0: perfect predictions, with no residual error left.
- 0.0: no better than a constant model that always predicts the mean of y and ignores every feature.
- Below 0: worse than that constant baseline. The model has learned a relationship that actively misleads, not just a weak one. There is no lower bound, because a model can be arbitrarily bad.
On the four-point example from the previous section, r2_score returns 0.948.
R² is built from squared error, so it ranks models in the same order as MSE on a given dataset. It does not discount outliers, however much data you collect. It also does not tell you whether large individual misses are rare. Two more limits matter in practice. The denominator depends on how much y varies in that particular dataset, so an R² of 0.8 on one dataset and 0.6 on another do not show which model is better. Also, r2_score reports the plain, unadjusted R² with no correction for sample size.
The true formula breaks down, because the variance of y is zero. It would give NaN for perfect predictions and -Inf for anything else. Non-finite values can break grid-search cross-validation, so r2_score replaces them by default with 1.0 (perfect) or 0.0 (imperfect). Passing force_finite=False returns the raw NaN or -inf.
Checkpoint 4 of 8· Check yourself
Two teams evaluate regression models with r2_score. Team A's model gets R² = 0.82 on Region A's sales data. Team B's model gets R² = 0.64 on Region B's sales data. What can you conclude about which model is better?
R²'s denominator is the variance of y in the dataset it is computed on. Scores from different datasets therefore do not show which model is better. Within one dataset, R² ranks models in the same order as MSE. r2_score reports unadjusted R², with no correction for sample size.
“As such variance is dataset dependent, \(R^2\) may not be meaningfully comparable across different datasets.”Source: scikit-learn.org
Checkpoint 5 of 8· Exam question
A data scientist is evaluating a regression model that predicts package delivery times. The historical dataset contains a handful of extreme outlier deliveries caused by rare shipping delays, and the team wants an evaluation metric whose value is not dominated by those few extreme residuals. Which metric best fits this requirement?
Correct answer: A — Mean absolute error, because it averages the absolute value of every residual and weights each error linearly, so a few large residuals do not dominate the score
- A. Mean absolute error sums the absolute residuals and divides by the count, so a single very large error contributes proportionally to its size rather than to its square, making it the metric least distorted by a handful of outliers.
- B. Root mean squared error squares each residual before averaging, so the rare large delivery-time errors contribute disproportionately to the final score, which is the opposite of what the team wants.
- C. R-squared reports explained variance relative to a mean baseline and does not become more robust to outliers as more data is collected; it is still computed from the same squared residuals used in RMSE.
- D. Mean squared error also squares residuals before averaging, so large errors are amplified rather than cancelled, meaning this metric is just as sensitive to the outliers as RMSE.
Checkpoint 6 of 8· Exam question
After training a regression model to predict house prices, a machine learning engineer evaluates it on a holdout set and finds an R-squared value of -0.15. What does this result indicate about the model?
Correct answer: A — The model fits the holdout data worse than a naive baseline that always predicts the average house price, so the learned relationship is actively misleading rather than simply weak
- A. R-squared compares the model's squared error against the squared error of always predicting the mean; a negative value means the fitted model performs worse than that trivial baseline, which is a genuine warning sign rather than a rounding artifact.
- B. R-squared is not a percentage scaled from zero to one hundred in this way, and a negative value does not mean the model is merely fifteen percent worse than perfect; it means the model underperforms the mean-prediction baseline.
- C. The coefficient of determination is only bounded above by one; it is unbounded below and can legitimately go negative whenever a model fits worse than the mean, so a negative value alone does not indicate a pipeline bug.
- D. Root mean squared error and mean absolute error are unrelated in magnitude to whether R-squared is negative, and neither metric is forced to zero by a negative coefficient of determination.
3.Relative, worst-case and log-scale variants
MAE, RMSE and R² all treat an error of 5 the same way whether the true value was 10 or 10,000. When that is the wrong question, other variants measure a different kind of error. In Databricks AutoML, primary_metric accepts only r2, mae, rmse and mse. You compute the other variants yourself, for example with sklearn.metrics, and log them to MLflow next to the standard ones.
predictions = lr.predict(train_x)
(rmse, mae, r2) = compute_metrics(train_y, predictions)
mlflow.log_metrics(
metrics={
"rmse": rmse,
"r2": r2,
"mae": mae,
},
model_id=logged_model.model_id,
dataset=train_dataset
)Mean absolute percentage error (MAPE) divides each absolute residual by the true value, so it measures relative error. Rescaling the whole target, for example from dollars to cents, does not change it. Take true values of 1, 10 and 1,000,000. MAE would be almost entirely the 200,000 miss on the largest value. MAPE weights the 10% miss on the value 1 as heavily as the 20% miss on the million. scikit-learn returns MAPE as a fraction, so 0.2666 means about 27%. Multiply by 100 to get the usual percentage.
Max error keeps only the single largest absolute residual. If the true values are [3, 2, 7, 1] and the predictions are [9, 2, 7, 1], max error is 6.0, while MAE is only 1.5. Use it when the worst case is what you are accountable for. Unlike the metrics above, it does not support multi-output targets. Median absolute error (MedAE) goes the other way: it takes the median of the absolute residuals, which makes it robust to outliers. Explained variance is scored like R², with 1.0 as the best value. It matches R² exactly when the residuals average to zero.
Mean squared logarithmic error (MSLE), and its square root RMSLE (root_mean_squared_log_error), apply a natural log to both the truth and the prediction before squaring the difference. That fits targets that grow exponentially, such as population counts or sales over several years, where a miss of 10 on 100 should count as much as a miss of 100 on 1,000. It also penalises under-predictions more than over-predictions of the same size. Normally a model trained on a log-transformed target must have its predictions exponentiated before scoring (see Exponentiate log-transformed predictions before metrics and interpretation). MSLE and RMSLE are the deliberate exception: they take raw-scale values and measure the error in log space on purpose.
| Metric | Measures | Reach for it when |
|---|---|---|
| mean_absolute_percentage_error | Relative error, as a fraction | Targets span orders of magnitude and small values matter |
| max_error | Single worst residual | The worst case is what gets reported |
| median_absolute_error | Typical residual, ignoring extremes | Outliers should not affect the score |
| mean_squared_log_error / root_mean_squared_log_error | Squared error of log values | Targets grow exponentially; under-forecasting is worse |
| explained_variance_score | Variance explained, like R² | Comparing to R² to check whether residuals are biased |
Checkpoint 7 of 8· Match them up
Match each evaluation need to the scikit-learn metric you would compute and log to MLflow next to RMSE, MAE and R².
Tap a term, then the definition that fits it.
MAPE divides each residual by the true value, so it measures relative error. max_error keeps only the worst residual. MedAE takes the median, so it ignores extreme rows. MSLE and RMSLE compare log values, which suits exponential growth, and they penalise under-predictions more.
“This metric is best to use when targets having exponential growth, such as population counts, average sales of a commodity over a span of years”Source: scikit-learn.org
4.Metric direction: minimised errors, maximised scores and neg_ scorers
Every metric on this page points one of two ways. Errors (MAE, MSE, RMSE, MAPE, MedAE, max error, MSLE) are lower-is-better, and 0 is perfect. Scores (R² and explained variance) are higher-is-better, and 1.0 is perfect. A tool that ranks models has to know which way a metric points. Mix them up and the tool picks the worst model with total confidence.
scikit-learn handles this with one rule: every scorer object returns a value where higher is better. Error metrics are therefore exposed as negated scorers. For example, scoring='neg_mean_squared_error' returns -MSE, so a tuner like GridSearchCV can always maximise. A best score of -0.375 means an MSE of 0.375, and -0.2 is better than -0.9. A negative value here is not a bug, and it is not a negative R². When you pass scoring=None, the estimator's own score method is used. For regressors that is R².
The same direction question comes up when you query MLflow. Suppose you search Logged Models with a filter like metrics.<metric_name> >= <metric_value>. That is the right comparison for r2 and the wrong one for rmse or mae, where you want <=. The same applies to the order you sort a leaderboard in. AutoML already knows the direction of each primary_metric it supports. Hand-written searches and comparisons do not, so check which way the metric points before writing the operator.
| Metric | Better when | Perfect value | scikit-learn scorer |
|---|---|---|---|
| MSE | Lower | 0 | neg_mean_squared_error |
| R² | Higher | 1.0 | r2 |
Checkpoint 8 of 8· Check yourself
GridSearchCV tuned with scoring='neg_mean_squared_error' reports best_score_ = -0.4. A teammate says this means the chosen model does worse than predicting the mean. How should the number be read?
scikit-learn scorers follow a higher-is-better convention, so error metrics are exposed negated: -0.4 is an MSE of 0.4, and -0.2 beats -0.9. A negative neg_ score is not a bug and has nothing to do with a negative R².
“All scorer objects follow the convention that higher return values are better than lower return values.”Source: scikit-learn.org
Sources
(5)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Supported metrics for regression: “r2” (default), “mae”, “rmse”, “mse””
↩︎ MSE, RMSE and MAE: squaring versus absolute value“Metric used to evaluate and rank model performance.”
↩︎ MSE, RMSE and MAE: squaring versus absolute value“primary_metric: str = "r2",”
↩︎ R-squared: error relative to predicting the mean - 2.https://docs.databricks.com/aws/en/machine-learning/ai-runtime/examples/tutorials/sgc-tabfmOfficial docs
“rmse = np.sqrt(mean_squared_error(y_test_reg, reg_pred))”
↩︎ MSE, RMSE and MAE: squaring versus absolute value - 3.
“sqrt(sum(errors$error^2 , na.rm = TRUE) / nrow(errors))”
↩︎ MSE, RMSE and MAE: squaring versus absolute value - 4.https://scikit-learn.org/stable/modules/model_evaluation.htmlSecondary source
“provides a measure in the same units as the target variable”
↩︎ MSE, RMSE and MAE: squaring versus absolute value“corresponding to the expected value of the absolute error loss”
↩︎ MSE, RMSE and MAE: squaring versus absolute value“median | absolute error | all reals | predict, all reals”
↩︎ MSE, RMSE and MAE: squaring versus absolute value“It represents the proportion of variance (of y) that has been explained by the independent variables in the model.”
↩︎ R-squared: error relative to predicting the mean“A constant model that always predicts the expected (average) value of y, disregarding the input features”
↩︎ R-squared: error relative to predicting the mean“R² gives the same ranking as squared error.”
↩︎ R-squared: error relative to predicting the mean“may not be meaningfully comparable across different datasets”
↩︎ R-squared: error relative to predicting the mean“the default behaviour of r2_score is to replace them with 1.0 (perfect predictions) or 0.0 (imperfect predictions)”
↩︎ R-squared: error relative to predicting the mean“It is for example not changed by a global scaling of the target variable.”
↩︎ Relative, worst-case and log-scale variants“a metric that captures the worst case error between the predicted value and the true value”
↩︎ Relative, worst-case and log-scale variants“Note that this metric penalizes an under-predicted estimate greater than an over-predicted estimate.”
↩︎ Relative, worst-case and log-scale variants“This metric is best to use when targets having exponential growth, such as population counts”
↩︎ Relative, worst-case and log-scale variants“All scorer objects follow the convention that higher return values are better than lower return values.”
↩︎ Metric direction: minimised errors, maximised scores and neg_ scorers“are available as ‘neg_mean_squared_error’ which return the negated value of the metric.”
↩︎ Metric direction: minimised errors, maximised scores and neg_ scorers“None: the estimator’s default evaluation criterion (i.e., the metric used in the estimator’s score method) is used.”
↩︎ Metric direction: minimised errors, maximised scores and neg_ scorers“provides a measure in the same units as the target variable”
↩︎ Key concept“The median_absolute_error is particularly interesting because it is robust to outliers.”
↩︎ Exam trap 1“Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse).”
↩︎ Exam trap 2“may not be meaningfully comparable across different datasets”
↩︎ Exam trap 3“All scorer objects follow the convention that higher return values are better than lower return values.”
↩︎ Exam trap 4“The median_absolute_error is particularly interesting because it is robust to outliers.”
↩︎ Checkpoint“Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse).”
↩︎ Prediction“As such variance is dataset dependent, \(R^2\) may not be meaningfully comparable across different datasets.”
↩︎ Checkpoint“This metric is best to use when targets having exponential growth, such as population counts, average sales of a commodity over a span of years”
↩︎ Checkpoint - 5.
“(rmse, mae, r2) = compute_metrics(train_y, predictions)”
↩︎ Relative, worst-case and log-scale variants“filter_string = "metrics.<metric_name> >= <metric_value>"”
↩︎ Metric direction: minimised errors, maximised scores and neg_ scorers