6. Regression Metrics
Mean Absolute Error (MAE) and Mean Squared Error (MSE) Definitions
In regression tasks, evaluating how well a model predicts continuous numerical values is critical. Two of the most foundational evaluation metrics are Mean Absolute Error (MAE) and Mean Squared Error (MSE). These metrics quantify the differences between the actual target values (ground truth) and the predicted values generated by the model.
Mean Absolute Error (MAE) calculates the average of the absolute differences between the actual and predicted values. It treats all errors equally and scale-wise reflects the average error magnitude. It is mathematically defined as the L1 norm of the error vector divided by the number of samples. Because it uses absolute values, it does not penalize large errors more than small errors.
Mean Squared Error (MSE) measures the average of the squares of the errors. By squaring the differences before averaging, MSE heavily penalizes larger errors. This corresponds to the L2 norm of the error vector. A prediction that is off by 10 units contributes 100 to the sum of squares, while a prediction off by 2 contributes only 4. This makes MSE highly sensitive to models that make occasional catastrophic errors.
import numpy as np from sklearn.metrics import mean_absolute_error, mean_squared_error y_true = np.array([3.0, -0.5, 2.0, 7.0]) y_pred = np.array([2.5, 0.0, 2.0, 8.0]) # Manual calculation mae_manual = np.mean(np.abs(y_true - y_pred)) mse_manual = np.mean((y_true - y_pred) ** 2) # Scikit-learn calculation mae_sklearn = mean_absolute_error(y_true, y_pred) mse_sklearn = mean_squared_error(y_true, y_pred) print(f'MAE (Manual): {mae_manual:.4f} | MAE (Sklearn): {mae_sklearn:.4f}') print(f'MSE (Manual): {mse_manual:.4f} | MSE (Sklearn): {mse_sklearn:.4f}')
Root Mean Squared Error (RMSE) and Sensitivity to Outliers
Root Mean Squared Error (RMSE) is simply the square root of the Mean Squared Error. Since MSE is calculated in squared units (e.g., squared dollars or squared meters), it can be difficult to interpret intuitively. RMSE resolves this by bringing the metric back to the original unit scale of the target variable.
However, because RMSE is based on MSE, it inherits the property of being extremely sensitive to outliers. When a dataset contains a few anomalous target values or wild prediction errors, the squaring operation in MSE/RMSE amplifies these errors dramatically, skewing the overall metric.
The table below highlights key properties of MAE, MSE, and RMSE to help you select the optimal metric for your business case:
| Metric | Formula Factor | Outlier Sensitivity | Unit Interpretability |
|---|---|---|---|
| MAE | Absolute value | Robust (Linear) | Directly interpretable |
| MSE | Squared error | High (Quadratic) | Hard to interpret (Squared units) |
| RMSE | Square root of MSE | High (Quadratic) | Directly interpretable |
import numpy as np from sklearn.metrics import mean_absolute_error, mean_squared_error # Standard predictions with minor errors y_true = np.array([10.0, 12.0, 11.0, 13.0, 12.0]) y_pred = np.array([9.8, 12.1, 10.9, 13.2, 11.8]) # Add one massive outlier prediction y_true_outlier = np.append(y_true, [15.0]) y_pred_outlier = np.append(y_pred, [5.0]) # Massive 10-unit error print('Standard Data:') print(f'MAE: {mean_absolute_error(y_true, y_pred):.4f}') print(f'RMSE: {np.sqrt(mean_squared_error(y_true, y_pred)):.4f}\n') print('With Single Extreme Outlier:') print(f'MAE: {mean_absolute_error(y_true_outlier, y_pred_outlier):.4f}') print(f'RMSE: {np.sqrt(mean_squared_error(y_true_outlier, y_pred_outlier)):.4f}')
Coefficient of Determination (R²) Interpretation
While MAE and RMSE tell us the absolute error scale of our predictions, they do not tell us how well our model performs relative to a simple, naive baseline. This is where the Coefficient of Determination, commonly known as R-squared (R²), comes in.
R² represents the proportion of variance in the dependent variable that is explained by the independent variables in the model. It compares the sum of squared residuals (errors of your model) to the total sum of squares (errors of a baseline model that always predicts the mean of the actual data).
An R² score of 1.0 indicates a perfect model that explains 100% of the variance. An R² score of 0.0 indicates a model that performs exactly as well as predicting the mean target value for every sample. A negative R² score indicates that the model's predictions are actually worse than simply predicting the mean of the dataset, highlighting severe model failure.
import numpy as np from sklearn.metrics import r2_score y_true = np.array([10.0, 20.0, 30.0, 40.0, 50.0]) # 1. Naive mean baseline prediction y_pred_mean = np.full_like(y_true, fill_value=np.mean(y_true)) # 2. A good predictive model y_pred_good = np.array([11.0, 19.0, 31.0, 38.0, 52.0]) # 3. A terrible model (worse than mean) y_pred_bad = np.array([50.0, 40.0, 30.0, 20.0, 10.0]) print(f'R2 of Mean Baseline: {r2_score(y_true, y_pred_mean):.4f}') print(f'R2 of Good Model: {r2_score(y_true, y_pred_good):.4f}') print(f'R2 of Bad Model: {r2_score(y_true, y_pred_bad):.4f}')
Custom Scoring Functions in Scikit-learn GridSearchCV
By default, Scikit-learn's model selection and tuning tools (like GridSearchCV or RandomizedSearchCV) use standard metric strings like neg_mean_squared_error or r2. However, in industrial machine learning, business constraints often dictate non-standard loss behaviors. For instance, underpredicting delivery times may be much more costly than overpredicting.
To solve this, Scikit-learn allows you to convert any custom Python evaluation function into a scorer using the make_scorer utility. A custom scorer can then be passed directly to the scoring parameter of cross-validation tools.
When creating a custom loss scorer, remember that scikit-learn's optimization search works on a 'higher is better' convention. Therefore, standard error-based loss functions (where lower is better) must be negated. Set greater_is_better=False inside make_scorer to ensure the parameter tuning algorithm properly minimizes the error.
import numpy as np from sklearn.datasets import make_regression from sklearn.linear_model import Ridge from sklearn.model_selection import GridSearchCV from sklearn.metrics import make_scorer # Generate synthetic data X, y = make_regression(n_samples=100, n_features=5, noise=5.0, random_state=42) # Define custom asymmetric cost: underpredicting by 1 costs 3x more than overpredicting def asymmetric_penalty(y_true, y_pred): error = y_pred - y_true # If error is negative (underpredicted), multiply by 3. If positive (overpredicted), multiply by 1 penalty = np.where(error < 0, 3 * np.abs(error), np.abs(error)) return np.mean(penalty) # Create a scorer. Since lower cost is better, set greater_is_better=False custom_scorer = make_scorer(asymmetric_penalty, greater_is_better=False) # Set up GridSearchCV with Ridge regression model = Ridge() param_grid = {'alpha': [0.1, 1.0, 10.0, 100.0]} grid_search = GridSearchCV(estimator=model, param_grid=param_grid, scoring=custom_scorer, cv=3) grid_search.fit(X, y) print('Best Hyperparameters:', grid_search.best_params_) print('Best Negative Score:', grid_search.best_score_)
Knowledge Check
Ready to test your understanding of 6. Regression Metrics?