Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 5 of 9
Regression Evaluation Metrics: MAE, MSE, RMSE, R², Adjusted R² & MAPE
Evaluating continuous predictions requires selecting the loss metric that matches business cost trade-offs. Mean Squared Error (MSE) and Root Mean Squared Error (RMSE) penalize large errors quadratically, making them ideal when extreme prediction misses are catastrophic. Mean Absolute Error (MAE) penalizes errors linearly, providing robust median estimates. R² measures explained variance relative to the mean baseline, and MAPE measures relative percentage error.
Comprehensive Regression Metric Comparison Engine
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score, mean_absolute_percentage_error
# Ground truth values vs model predictions (with 1 catastrophic outlier prediction)
np.random.seed(42)
y_true = np.array([100.0, 150.0, 200.0, 250.0, 300.0, 350.0, 400.0, 450.0, 500.0, 1000.0])
# Model A: small consistent errors everywhere
y_pred_A = y_true + np.random.normal(0, 15, size=len(y_true))
# Model B: perfect on 9 samples, but off by 500 on the last outlier sample
y_pred_B = y_true.copy()
y_pred_B[-1] = 500.0 # Missed 1000.0 by 500!
def compute_regression_metrics(y_real, y_hat, n_features=1):
n = len(y_real)
mae = mean_absolute_error(y_real, y_hat)
mse = mean_squared_error(y_real, y_hat)
rmse = np.sqrt(mse)
mape = mean_absolute_percentage_error(y_real, y_hat) * 100
r2 = r2_score(y_real, y_hat)
# Adjusted R^2 penalizes superfluous features: 1 - [(1 - R^2)(n - 1) / (n - p - 1)]
adj_r2 = 1.0 - ((1.0 - r2) * (n - 1) / (n - n_features - 1))
return {
'MAE': f"{mae:.2f}",
'RMSE': f"{rmse:.2f}",
'MAPE': f"{mape:.2f}%",
'R^2': f"{r2:.4f}",
'Adjusted R^2': f"{adj_r2:.4f}"
}
metrics_A = compute_regression_metrics(y_true, y_pred_A)
metrics_B = compute_regression_metrics(y_true, y_pred_B)
df_eval = pd.DataFrame([metrics_A, metrics_B], index=['Model A (Uniform Noise)', 'Model B (Single Huge Outlier)'])
print("=== REGRESSION METRIC SENSITIVITY BENCHMARK ===")
print(df_eval.to_string())
print("\nNotice: Model B has lower MAE (50.0) but massive RMSE (158.11) due to quadratic penalization!")Pro Tip: When to Use MAPE vs WAPE
Mean Absolute Percentage Error (MAPE) divides by the true value `|y - y_hat| / y`. If actual y contains values near zero (e.g. daily store sales of 0 or 1), MAPE explodes to thousands of percent. Use Weighted Absolute Percentage Error (WAPE = `sum(|y - y_hat|) / sum(y)`) instead to stabilize relative error calculations.
MlRegressionMetrics Visual Representation
Hands-On Challenge: Build a Huber Loss Function
Implement the Huber Loss function from scratch in Python: `L_delta(r) = 0.5 * r^2 if |r| <= delta else delta * (|r| - 0.5 * delta)`. Demonstrate how Huber loss smoothly transitions from quadratic MSE for small errors to linear MAE for large outliers.
Quick Quiz & Key Concept Checks
Common Pitfall: Averaging Percentage Errors Across Heterogeneous Volumes
A 50% forecasting error on a product selling 2 units a month represents 1 unit of variance. A 50% error on a product selling 100,000 units represents 50,000 units of lost inventory. Unweighted MAPE treats both errors as equally catastrophic. Always weight errors by economic volume.