CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 3 · Lesson 39/48

    Regression metrics: MSE, RMSE, MAE and R-squared

    Use common regression metrics: RMSE, MAE, R-squared, etc.

    17 min read
    2.07% of exam
    5 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    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.

    MAE on four predictions: residuals of 0.5, -0.5, 0 and -1 average to 0.5 in absolute valuepython
    >>> 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.5

    Running 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.
    How each error metric treats a residual
    MetricPer-row treatmentUnitsEffect of a few huge residuals
    MAE (mean_absolute_error)Absolute value, averagedSame as targetGrows linearly with them
    MSE (mean_squared_error)Squared, averagedTarget units squaredDominated by them
    RMSE (root_mean_squared_error)Square root of MSESame as targetDominated by them
    MedAE (median_absolute_error)Median of absolute residualsSame as targetRobust 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)

    Checkpoint 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?

    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?

    Sources1234

    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.

    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?

    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?

    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?

    Sources14

    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.

    Logging RMSE, MAE and R² against an MLflow LoggedModelpython
    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.

    Choosing a variant by the kind of error that matters
    MetricMeasuresReach for it when
    mean_absolute_percentage_errorRelative error, as a fractionTargets span orders of magnitude and small values matter
    max_errorSingle worst residualThe worst case is what gets reported
    median_absolute_errorTypical residual, ignoring extremesOutliers should not affect the score
    mean_squared_log_error / root_mean_squared_log_errorSquared error of log valuesTargets grow exponentially; under-forecasting is worse
    explained_variance_scoreVariance 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.

    Sources54

    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.

    Direction of common regression metrics
    MetricBetter whenPerfect valuescikit-learn scorer
    MSELower0neg_mean_squared_error
    R²Higher1.0r2

    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?

    Sources54

    Sources

    (5)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 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
    2. 3.
      “sqrt(sum(errors$error^2 , na.rm = TRUE) / nrow(errors))”
      ↩︎ MSE, RMSE and MAE: squaring versus absolute value
    3. 4.
      “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
    4. 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

    Ready to test yourself?

    Practise the 7 questions on this subdomain.

    Spotted a mistake, or was something unclear? Tell us.