Regression Metrics Explained: MSE, RMSE, MAE, and R²

When building a regression model to predict continuous values—such as house prices, stock prices, salaries, or server latency—you cannot evaluate its performance using classification accuracy.

Instead, you need to measure the difference between the model's predictions (\(\hat{y}_i\)) and the actual ground-truth values (\(y_i\)).

The four most widely used regression evaluation metrics are:

  • Mean Squared Error (MSE)
  • Root Mean Squared Error (RMSE)
  • Mean Absolute Error (MAE)
  • Coefficient of Determination (R²)

Each metric evaluates prediction errors differently. Some penalize large errors more heavily, while others provide an easily interpretable measure of average prediction error.

Choosing the wrong evaluation metric can give you an unrealistic understanding of how your regression model performs in production.

In this guide, we will explore these four metrics using mathematical formulas, numerical examples, Python implementation, and practical use cases.


1. Understanding Regression Prediction Errors

Before exploring regression evaluation metrics, let's understand how prediction errors are calculated.

A regression model predicts continuous numerical values.

For example, suppose we build a house-price prediction model.

HouseActual PricePredicted Price
House 1₹50 lakh₹48 lakh
House 2₹60 lakh₹65 lakh
House 3₹75 lakh₹72 lakh
House 4₹90 lakh₹95 lakh
House 5₹100 lakh₹98 lakh

The difference between an actual value and a predicted value is called the Residual or prediction error.

\[ e_i = y_i-\hat{y}_i \]

Where:

  • \(y_i\) = Actual value.
  • \(\hat{y}_i\) = Predicted value.
  • \(e_i\) = Prediction error or residual.

A positive residual means the model underpredicted the actual value.

A negative residual means the model overpredicted the actual value.

For example:

\[ e_1=50-48=2 \]

The model underpredicted House 1's price by ₹2 lakh.

Similarly:

\[ e_2=60-65=-5 \]

The model overpredicted House 2's price by ₹5 lakh.

Regression metrics summarize these errors across all observations.


2. Mean Absolute Error (MAE)

Mean Absolute Error (MAE) calculates the average of the absolute differences between predicted values and actual target values.

It measures how far the model's predictions are from the actual values, on average.

Mathematical Formula

\[ MAE=\frac{1}{n}\sum_{i=1}^{n}|y_i-\hat{y}_i| \]

Where:

  • \(n\) = Total number of observations.
  • \(y_i\) = Actual value.
  • \(\hat{y}_i\) = Predicted value.
  • \(|y_i-\hat{y}_i|\) = Absolute prediction error.

Example

Suppose a model predicts the following house prices:

HouseActual PricePredicted PriceAbsolute Error
House 150482
House 260655
House 375723
House 490955
House 5100982
Total17

All prices are in ₹ lakh.

Now calculate MAE:

\[ MAE=\frac{2+5+3+5+2}{5} \]

\[ MAE=\frac{17}{5} \]

\[ \boxed{MAE=3.4\text{ lakh}} \]

This means the model's average absolute prediction error is ₹3.4 lakh.

Key Characteristics of MAE

1. Original Units

MAE is expressed in the same units as the target variable.

For example:

  • House prices: ₹ lakh.
  • Server latency: milliseconds.
  • Temperature: °C.
  • Weight: kilograms.

This makes MAE easy to explain to business stakeholders.

2. Linear Penalty

MAE penalizes errors proportionally to their absolute magnitude.

For example:

  • Error of 5 contributes 5.
  • Error of 10 contributes 10.
  • Error of 20 contributes 20.

An error of 10 contributes twice as much as an error of 5.

3. Less Sensitive to Outliers

MAE does not square prediction errors. Therefore, large errors do not dominate the metric as strongly as they do with MSE or RMSE.

However, MAE is not completely robust to outliers. A sufficiently large error still increases its value.

4. Less Smooth for Optimization

MAE is not differentiable at zero residual, although it has a well-defined subgradient there. Optimization methods can still use MAE, but its optimization behavior differs from that of MSE.

When to Use MAE

Use MAE when:

  • You want an understandable average prediction error.
  • Large errors should not receive disproportionately greater penalties.
  • Your dataset contains extreme observations or noisy measurements.
  • Your business objective is to minimize average absolute prediction error.

Real-world example: A property website wants to communicate how far its estimated house prices are from actual selling prices on average. MAE is a useful metric for this purpose.


3. Mean Squared Error (MSE)

Mean Squared Error (MSE) calculates the average of the squared differences between actual values and predicted values.

Unlike MAE, MSE squares every prediction error before averaging.

Mathematical Formula

\[ MSE=\frac{1}{n}\sum_{i=1}^{n}(y_i-\hat{y}_i)^2 \]

Where:

  • \(n\) = Total number of observations.
  • \(y_i\) = Actual value.
  • \(\hat{y}_i\) = Predicted value.
  • \((y_i-\hat{y}_i)^2\) = Squared prediction error.

Example

Using our previous house-price example:

HouseActual PricePredicted PriceSquared Error
House 150484
House 2606525
House 375729
House 4909525
House 5100984
Total67

Now calculate MSE:

\[ MSE=\frac{4+25+9+25+4}{5} \]

\[ MSE=\frac{67}{5} \]

\[ \boxed{MSE=13.4} \]

The unit is squared, so the result is expressed in \((₹\text{ lakh})^2\).

Key Characteristics of MSE

1. Quadratic Penalty

MSE penalizes large prediction errors more heavily because errors are squared.

For example:

Prediction ErrorSquared Error
24
525
10100
20400

An error of 10 contributes four times as much as an error of 5.

An error of 20 contributes 100 times as much as an error of 2.

2. Sensitive to Outliers

A single extremely large prediction error can significantly increase MSE.

This is useful when large prediction mistakes are especially costly, but it can also make the metric difficult to interpret when the dataset contains noisy extreme observations.

3. Squared Output Units

MSE is expressed in squared target units.

For example:

  • Price: rupees squared.
  • Latency: milliseconds squared.
  • Weight: kilograms squared.

This makes it less intuitive for business reporting.

4. Useful for Optimization

MSE is differentiable everywhere and has a simple gradient.

For a prediction \(\hat{y}\), the squared-error contribution is:

\[ L=(y-\hat{y})^2 \]

Its derivative with respect to the prediction is:

\[ \frac{\partial L}{\partial \hat{y}} =2(\hat{y}-y) \]

This property makes MSE convenient for gradient-based optimization.

When to Use MSE

Use MSE when:

  • Large prediction errors must be penalized more heavily.
  • You are training models using gradient-based optimization.
  • You want to minimize squared prediction error.
  • Your application benefits from a loss function that emphasizes large deviations.

Real-world example: In server-latency prediction, extremely inaccurate estimates may cause poor capacity planning. MSE can penalize these large prediction errors more strongly.


4. Root Mean Squared Error (RMSE)

Root Mean Squared Error (RMSE) is the square root of Mean Squared Error.

It measures the typical magnitude of prediction errors while retaining the squared-error penalty used by MSE.

Mathematical Formula

\[ RMSE=\sqrt{\frac{1}{n} \sum_{i=1}^{n}(y_i-\hat{y}_i)^2} \]

Alternatively:

\[ RMSE=\sqrt{MSE} \]

Example

From our previous calculation:

\[ MSE=13.4 \]

Therefore:

\[ RMSE=\sqrt{13.4} \]

\[ \boxed{RMSE\approx3.66\text{ lakh}} \]

This means the model's RMSE is approximately ₹3.66 lakh.

Key Characteristics of RMSE

1. Original Units Restored

Unlike MSE, RMSE is expressed in the same units as the target variable.

This makes it easier to understand and communicate.

2. Sensitive to Large Errors

RMSE retains the squared-error penalty before taking the square root.

Therefore, large prediction errors have a greater influence on RMSE than on MAE.

3. Relationship Between RMSE and MAE

For the same observations and the same nonnegative sample weights:

\[ \boxed{RMSE\geq MAE} \]

This relationship follows from the mathematical relationship between the quadratic mean and arithmetic mean of nonnegative absolute errors.

4. Useful for Model Comparison

RMSE is commonly used to compare regression models when large prediction errors deserve additional attention.

However, the models must be evaluated on the same target scale and comparable datasets.

When to Use RMSE

Use RMSE when:

  • Large prediction errors are more costly than small ones.
  • You need an error metric in the original target units.
  • You want to compare regression models using squared-error performance.
  • You are working on forecasting or engineering applications where large deviations matter.

Real-world example: A real-estate company wants to evaluate house-price predictions and considers large pricing mistakes more serious than small ones. RMSE can be a useful evaluation metric.


5. R-Squared (R²): Coefficient of Determination

While MAE, MSE, and RMSE measure prediction errors, R-Squared (R²) measures how well a regression model performs relative to a baseline that always predicts the mean of the actual target values.

It is known as the Coefficient of Determination.

R² compares the model's residual sum of squares against the total sum of squares.

Mathematical Formula

\[ R^2=1-\frac{SS_{res}}{SS_{tot}} \]

Where:

Residual Sum of Squares:

\[ SS_{res}=\sum_{i=1}^{n}(y_i-\hat{y}_i)^2 \]

Total Sum of Squares:

\[ SS_{tot}=\sum_{i=1}^{n}(y_i-\bar{y})^2 \]

Where:

  • \(y_i\) = Actual value.
  • \(\hat{y}_i\) = Predicted value.
  • \(\bar{y}\) = Mean of actual target values.

Understanding R² Values

R² ValueInterpretation
1.00Perfect predictions on the evaluated observations
0.80Model explains 80% of the variation relative to the mean baseline
0.50Model performs better than the mean baseline, but leaves substantial residual variation
0.00Model has the same squared error as predicting the mean
Below 0Model performs worse than the mean-prediction baseline

Important: R² is not necessarily the percentage of predictions that are correct. It is not classification accuracy.

A negative R² is possible, especially on unseen test data. It means the model's squared prediction errors are greater than those of the baseline that predicts the evaluation-set mean.

Example

Suppose the actual house prices are:

\[ y=[50,60,75,90,100] \]

The average actual price is:

\[ \bar{y}=\frac{50+60+75+90+100}{5} \]

\[ \bar{y}=75 \]

Our model's squared errors total:

\[ SS_{res}=67 \]

Now calculate the total sum of squares:

\[ SS_{tot}=(50-75)^2+(60-75)^2 \]

\[ +(75-75)^2+(90-75)^2+(100-75)^2 \]

\[ SS_{tot}=625+225+0+225+625 \]

\[ SS_{tot}=1700 \]

Substitute these values into the R² formula:

\[ R^2=1-\frac{67}{1700} \]

\[ R^2=1-0.0394 \]

\[ \boxed{R^2\approx0.9606=96.06\%} \]

This means the model's squared prediction error is approximately 3.94% of the squared error produced by the mean-prediction baseline.

The model explains approximately 96.06% of the variation relative to that baseline on these observations.

When to Use R²

Use R² when:

  • You want to compare model performance relative to a mean-prediction baseline.
  • You want a dimensionless summary of regression performance.
  • You are comparing models on the same target and evaluation dataset.
  • You want to understand how much variation is accounted for by the fitted model.

Important limitation: R² does not measure the practical size of prediction errors. A model can have a high R² and still make errors that are too large for a business application.


6. Adjusted R²: Accounting for Additional Features

In multiple linear regression, adding more predictors can improve or maintain ordinary training R², even when the new predictors provide little useful information.

To account for the number of predictors, we can use Adjusted R².

Mathematical Formula

\[ Adjusted\ R^2= 1-(1-R^2)\frac{n-1}{n-p-1} \]

Where:

  • \(n\) = Number of observations.
  • \(p\) = Number of independent variables or predictors.
  • \(R^2\) = Ordinary coefficient of determination.

Why Is Adjusted R² Useful?

Suppose we build two regression models:

  • Model A uses 3 independent variables.
  • Model B uses 15 independent variables.

Model B may achieve a higher training R² simply because it has more predictors.

Adjusted R² introduces a penalty for adding predictors relative to the available observations.

It can help identify whether additional features provide enough improvement to justify the increased model complexity.

When to Use Adjusted R²

  • Multiple linear regression.
  • Comparing models with different numbers of predictors.
  • Evaluating whether additional features provide meaningful improvement.

Important: Adjusted R² is mainly a model-comparison statistic for linear regression settings. It is not a replacement for validation or test-set evaluation. It can decrease when predictors are added, and its interpretation depends on the model and data assumptions.


7. Comparison Matrix: MAE vs. MSE vs. RMSE vs. R²

Let's compare the four major regression metrics.

MetricFormulaOutput UnitsOutlier SensitivityBest Used For
MAEAverage absolute errorOriginal unitsLower than squared-error metricsInterpretable average prediction error
MSEAverage squared errorSquared unitsVery highTraining and penalizing large errors
RMSESquare root of MSEOriginal unitsHighReporting errors with additional emphasis on large deviations
R²\(1-SS_{res}/SS_{tot}\)DimensionlessSensitive to large squared residualsPerformance relative to a mean baseline

Understanding the Differences

  • MAE: Tells you how far predictions are from actual values on average.
  • MSE: Penalizes large errors quadratically.
  • RMSE: Expresses squared-error performance in the original target units.
  • R²: Compares the model's squared error with a simple mean-prediction baseline.

No single metric is universally best. The correct choice depends on your problem and the cost of prediction errors.


8. Practical Metric Selection Guide

To choose the right regression metric, first understand the consequences of prediction errors in your application.

Scenario 1: Are Large Errors Much More Expensive?

Yes: Consider RMSE for reporting and MSE for optimization.

Examples:

  • House-price prediction where major pricing mistakes are costly.
  • Electricity demand forecasting.
  • Server resource planning.

No: MAE may be more suitable because it treats absolute errors proportionally.

Examples:

  • Delivery-time prediction.
  • General sales forecasting.
  • Estimating average customer spending.

Scenario 2: Do You Need an Easily Interpretable Error?

Use MAE or RMSE because both use the same units as the target variable.

For example:

  • MAE = 5 minutes.
  • RMSE = 8 minutes.

These values are easier to explain than MSE = 64 minutes².

Scenario 3: Do You Want to Compare Against a Baseline?

Use R² to understand how much better or worse your model performs than predicting the mean.

However, do not use R² alone when actual prediction errors have important business consequences.

Scenario 4: Does Your Dataset Contain Extreme Outliers?

Consider MAE if you do not want a few unusually large errors to dominate the metric.

You should also investigate the outliers to determine whether they represent measurement errors, rare but valid events, or an important part of the problem.

Quick Decision Table

RequirementRecommended Metric
Average absolute prediction errorMAE
Penalize large prediction errorsMSE
Penalize large errors in original unitsRMSE
Compare against mean baselineR²
Compare linear models with different predictor countsAdjusted R²

9. Python Implementation: Calculating Regression Metrics

Now let's calculate MAE, MSE, RMSE, and R² using Python and Scikit-learn.

Scikit-learn provides built-in functions to evaluate regression models.

Step 1: Install Required Libraries

pip install numpy pandas scikit-learn matplotlib

Step 2: Import Libraries

import numpy as np
import pandas as pd

from sklearn.metrics import (
    mean_absolute_error,
    mean_squared_error,
    r2_score
)

Step 3: Create Actual and Predicted Values

Let's use the same house-price example.

# Actual house prices
y_actual = np.array([
    50, 60, 75, 90, 100
])

# Predicted house prices
y_pred = np.array([
    48, 65, 72, 95, 98
])

Step 4: Calculate MAE

mae = mean_absolute_error(
    y_actual,
    y_pred
)

print("MAE:", mae)

Output:

MAE: 3.4

The model's average absolute error is ₹3.4 lakh.

Step 5: Calculate MSE

mse = mean_squared_error(
    y_actual,
    y_pred
)

print("MSE:", mse)

Output:

MSE: 13.4

Step 6: Calculate RMSE

rmse = np.sqrt(mse)

print("RMSE:", rmse)

Output:

RMSE: 3.6606

Step 7: Calculate R² Score

r2 = r2_score(
    y_actual,
    y_pred
)

print("R2 Score:", r2)

Output:

R2 Score: 0.9606

Step 8: Display All Metrics Together

results = {
    "MAE": mae,
    "MSE": mse,
    "RMSE": rmse,
    "R2 Score": r2
}

for metric, value in results.items():
    print(f"{metric}: {value:.4f}")

Expected Output:

MAE: 3.4000
MSE: 13.4000
RMSE: 3.6606
R2 Score: 0.9606

This gives us a complete evaluation of the regression model.


10. Visualizing Actual vs. Predicted Values

Numerical evaluation metrics are useful, but visualization can help you understand how well the model's predictions match actual values.

An Actual vs. Predicted plot compares the model's predictions against the ground-truth values.

import matplotlib.pyplot as plt

plt.figure(figsize=(7, 5))

plt.scatter(
    y_actual,
    y_pred
)

# Ideal prediction line
minimum = min(y_actual.min(), y_pred.min())
maximum = max(y_actual.max(), y_pred.max())

plt.plot(
    [minimum, maximum],
    [minimum, maximum],
    linestyle="--",
    label="Perfect Prediction"
)

plt.xlabel("Actual House Prices")
plt.ylabel("Predicted House Prices")

plt.title("Actual vs Predicted Values")

plt.legend()
plt.grid(True)

plt.show()

How to Interpret the Plot

  • Points close to the diagonal line indicate accurate predictions.
  • Points above the line indicate overprediction.
  • Points below the line indicate underprediction.
  • Large distances from the diagonal indicate larger prediction errors.

This visualization helps identify systematic prediction problems that a single metric might hide.


11. Residual Analysis: Understanding Model Errors

A regression model should not be evaluated using only its overall error metrics.

You should also examine its residuals.

A Residual Plot displays prediction errors against predicted values or another relevant variable.

\[ Residual = Actual-Predicted \]

Why Is Residual Analysis Important?

It can help identify:

1. Non-Linearity

If residuals show a curved pattern, the model may not be capturing a nonlinear relationship.

2. Heteroscedasticity

If the spread of residuals changes with predicted values, the error variance may not be constant.

3. Outliers

Extremely large residuals may indicate unusual observations or poor predictions.

4. Systematic Bias

If residuals are consistently positive or negative in certain regions, the model may systematically underpredict or overpredict.

Python: Residual Plot

residuals = y_actual - y_pred

plt.figure(figsize=(7, 5))

plt.scatter(
    y_pred,
    residuals
)

plt.axhline(
    y=0,
    linestyle="--"
)

plt.xlabel("Predicted Values")
plt.ylabel("Residuals")

plt.title("Residual Plot")

plt.grid(True)

plt.show()

A well-behaved residual plot for a suitable model often shows residuals scattered around zero without strong systematic patterns.

Residual analysis is particularly important when you want to understand whether the model's assumptions are reasonable.


12. Other Regression Metrics You Should Know

Although MAE, MSE, RMSE, and R² are among the most common regression metrics, other evaluation measures are also useful.

12.1 Mean Absolute Percentage Error (MAPE)

MAPE measures average absolute prediction error as a percentage of actual values.

\[ MAPE=\frac{100\%}{n} \sum_{i=1}^{n} \left|\frac{y_i-\hat{y}_i}{y_i}\right| \]

When to Use:

  • Sales forecasting.
  • Demand forecasting.
  • Business forecasting where percentage errors are meaningful.

Limitation: MAPE is undefined when actual values are zero and can become extremely large when actual values are close to zero. It can also behave asymmetrically for overpredictions and underpredictions.

12.2 Median Absolute Error

Median Absolute Error calculates the median of all absolute prediction errors.

\[ MedAE=Median(|y_i-\hat{y}_i|) \]

When to Use:

  • Datasets containing extreme outliers.
  • Applications where the typical prediction error matters more than the average.
  • Robust regression evaluation.

12.3 Mean Absolute Scaled Error (MASE)

MASE compares a model's forecast error against a simple naïve forecasting baseline.

It is particularly useful in time-series forecasting because it provides a scale-independent way to compare forecast errors.

A MASE below 1 indicates that the model performs better than the selected naïve baseline under the same evaluation setup.

12.4 Adjusted R²

Adjusted R² accounts for the number of predictors in a multiple regression model.

It is useful when comparing linear regression models with different numbers of independent variables.


13. Common Mistakes When Evaluating Regression Models

Even when the correct formulas are used, several mistakes can lead to misleading regression evaluation results.

1. Using Only R²

A high R² does not guarantee that the model's prediction errors are small enough for practical use.

Solution: Report MAE or RMSE alongside R².

2. Ignoring Outliers

A few extreme observations can significantly increase MSE and RMSE.

Solution: Examine residuals and compare MAE with RMSE.

3. Comparing Metrics Across Different Target Scales

MAE and RMSE depend on the units and scale of the target variable.

Solution: Compare these metrics directly only when target scales and evaluation conditions are comparable. Consider normalized metrics when appropriate.

4. Treating Negative R² as a Calculation Error

R² can legitimately be negative on test data.

Solution: Compare model performance against the mean-prediction baseline and investigate why the model performs poorly.

5. Evaluating Only Training Performance

A model may perform extremely well on training data but poorly on unseen observations.

Solution: Use separate training, validation, and test datasets or appropriate cross-validation.

6. Ignoring Data Leakage

Using information from validation or test data during model training can produce overly optimistic evaluation results.

Solution: Fit preprocessing, feature selection, and transformations only on training data, preferably through a Scikit-learn Pipeline.

7. Ignoring the Business Objective

A model with the lowest RMSE is not necessarily the best model for every business problem.

Solution: Select evaluation metrics based on the real-world cost of prediction errors.


14. Best Practices for Regression Model Evaluation

Follow these practices to build more reliable regression models:

  1. Understand Your Target Variable: Check its scale, distribution, and units.
  2. Use Multiple Metrics: Evaluate MAE, RMSE, and R² together when appropriate.
  3. Compare Against a Baseline: Check whether your model improves on a simple mean or naïve prediction.
  4. Inspect Residuals: Identify outliers, systematic bias, and unusual error patterns.
  5. Use Cross-Validation: Evaluate model stability across different data splits.
  6. Avoid Data Leakage: Keep preprocessing and feature selection inside the training workflow.
  7. Evaluate on Unseen Data: Use a separate test set for final performance measurement.
  8. Understand Outlier Effects: Choose MAE, MSE, or RMSE according to how large errors should be penalized.
  9. Consider Business Costs: A small average error may still be unacceptable for high-value predictions.
  10. Monitor Production Performance: Track prediction errors as new actual outcomes become available.

Conclusion

MSE, RMSE, MAE, and R² are fundamental metrics for evaluating regression models, but each measures a different aspect of prediction performance.

MAE measures average absolute prediction error and is relatively less sensitive to extreme errors.

MSE squares prediction errors, making large mistakes more costly.

RMSE takes the square root of MSE, restoring the original target units while retaining sensitivity to large errors.

R² measures how well the model performs relative to a baseline that predicts the mean of the actual target values.

The best metric depends on the problem you are solving.

For easily understandable average errors, MAE is useful. For applications where large prediction errors are especially costly, RMSE is often a better choice. For understanding performance relative to a mean baseline, R² provides useful information.

However, no single metric tells the complete story.

A reliable regression evaluation strategy combines multiple metrics, residual analysis, cross-validation, and business-specific requirements.

Remember: A good regression model is not simply the one with the highest R² or lowest RMSE. It is the model that produces sufficiently accurate and dependable predictions for the problem it is designed to solve.