Regression Model Evaluation
In the world of machine learning, building a model is only the first step. It is like baking a cake: you must taste it to know whether it succeeded. For a regression model (a model used to predict continuous numerical values, such as house prices, temperature, or sales),Model evaluationis ourtastingstage. It tells us how accurate the model's predictions are, what it does well, and where there is room for improvement.
This article will guide you through a systematic study of regression model evaluation methods, from core concepts to specific metrics and then to hands-on code, so that you can not only understand evaluation reports but also "score" your model yourself.
Core concepts of regression models and evaluation
Before diving into metrics, we need to understand a few basic concepts, which are the foundation of all evaluation methods.
What is a regression problem?
A regression problem is a type of supervised learning whose goal is to predict acontinuous numerical value。
- Examplebased on input features: for example, predicting a house's sale price (a continuous value) from its area, age, and location (features).
Why is evaluation needed?
- Model selection: to compare which of different algorithms (such as linear regression and decision tree regression) performs better on your data.
- Parameter tuning: when tuning model parameters (such as regularization strength), an objective criterion is needed to judge whether the adjustment is effective.
- Performance confirmation: to ensure the model also has reliable predictive power on unseen data, avoiding "armchair theorizing".
Key term: error
All evaluation metrics revolve around "error". Error is the difference between the model's predicted value (ŷ) and the true value (y).
- Error at a single point:
误差 = y - ŷ - The essence of evaluation isto summarize and analyze these errors in different ways。
Core evaluation metrics explained in detail
We will introduce the most commonly used and most important evaluation metrics, using a simple example throughout.
Suppose we predicted the prices of 5 houses:
| True price (y) | Predicted price (ŷ) | Error (y - ŷ) |
|---|---|---|
| 200 | 210 | -10 |
| 150 | 145 | 5 |
| 300 | 310 | -10 |
| 400 | 380 | 20 |
| 250 | 255 | -5 |
1. Mean Absolute Error (MAE)
Plain-language understanding: add up the absolute values of all prediction "errors" and then take the average. It directly reflects "on average, by how many units the predicted value deviates from the true value".
Calculation Formula: MAE = (1/n) * Σ|y_i - ŷ_i| where n is the number of samples,Σ is the summation symbol.
Calculation example: MAE = (|-10| + |5| + |-10| + |20| + |-5|) / 5 = (10+5+10+20+5)/5 = 50/5 = 10
Interpretation: on average, our house price predictions deviate from the true prices by 100,000 yuan。
Feature:
- Advantages: intuitive and easy to understand, and not overly affected by extreme error values (outliers).
- Disadvantages: the absolute value function is not differentiable everywhere mathematically, which is inconvenient in some optimization scenarios.
2. Mean Squared Error (MSE)
Plain-language understanding: first "square" each error (making the negative sign disappear and amplifying the error), and then take the average. It is very sensitive tolarge errors。
Calculation Formula: MSE = (1/n) * Σ(y_i - ŷ_i)^2
Calculation example: MSE = [(-10)^2 + (5)^2 + (-10)^2 + (20)^2 + (-5)^2] / 5 = (100+25+100+400+25)/5 = 650/5 = 130
Interpretation: the average of the squared errors is 130. This number itself has no direct unit meaning (it is in units of (10,000 yuan)^2), but it is very effective for comparing models.
Feature:
- Advantages: excellent mathematical properties (differentiable everywhere), and it is the objective function minimized during training for many models (such as linear regression).
- Disadvantages: its dimension differs from the original data, so the magnitude is not easy to interpret; it is sensitive to outliers.
3. Root Mean Squared Error (RMSE)
Plain-language understanding: it is the square root of MSE. It is like turning MSE "back into its original form", bringing it onto the same scale as the true values and predicted values.
Calculation Formula: RMSE = sqrt(MSE)
Calculation example: RMSE = sqrt(130) ≈ 11.4
Interpretation: on average, our predictions deviate from the true values by about 114,000 yuan. This interpretation is similar to MAE (100,000 yuan), but because RMSE squares and then takes the square root, it gives higher weight to large errors, so it is usually larger than MAE.
Feature:
- Advantages: it has the same dimension as the original data, making it more interpretable than MSE; it penalizes large errors more heavily, and is commonly used in scenarios where large errors matter (such as financial risk prediction).
- Disadvantages: it is also sensitive to outliers.
4. R² score (coefficient of determination)
Plain-language understanding: how much better is my model than "blind guessing" (guessing with the average)? It is aproportional value, measuring the model's ability to explain the variation in the data.
Calculation Formula: R² = 1 - (Σ(y_i - ŷ_i)^2 / Σ(y_i - y_mean)^2) where y_mean is the average of the true values.
"blind guessing" model: for any house, I predict the average house price (y_mean)。
- computed as
y_mean = (200+150+300+400+250)/5 = 260 - sum of squared errors of the "blind guessing" model:
Σ(y_i - 260)^2 = 1600+12100+1600+19600+100 = 35000
Calculation example: R² = 1 - (650 / 35000) = 1 - 0.01857 ≈ 0.9814
Interpretation: our model can explain the fluctuation of the target variable (house price)98.14% . This indicates the model fits very well.
Feature:
- Range: theoretically, the range of R² is
(-∞, 1]。 R² = 1: perfect prediction.R² = 0: the model performs the same as simply predicting with the average.R² < 0: the model performs worse than simply predicting with the average (indicating the model is completely unsuitable for the data).
- Advantages: dimensionless, making it easy to compare model performance across different datasets.
- Disadvantages: as the number of model features increases, R² naturally increases even if the added features are useless, which may lead to overfitting.
Metric comparison and how to choose
For a clearer understanding, let us summarize with a table:
| Pointer | Calculation formula (abbreviated) | Dimension | Sensitivity to outliers | Features and applicable scenarios |
|---|---|---|---|---|
| MAE | Mean absolute error | same as y | not sensitive | most intuitive to interpret. It focuses on "how large the average deviation is" and applies to all regression scenarios, especially data with many outliers. |
| MSE | Mean Squared Error | y squared | very sensitive | good mathematical properties. It is a commonly used loss function for model training. The value itself is not easy to interpret. |
| RMSE | square root of MSE | same as y | very sensitive | Most commonly used. It combines the mathematical advantages of MSE with interpretability. It penalizes large errors heavily and is popular in fields such as finance and forecasting. |
| R² | 1 - (model error / baseline error) | dimensionless | sensitive | relative performance metric. Used to compare how much a model improves relative to a simple baseline. Easy to compare across datasets. |
Selection recommendations:
- Report RMSE and R² first: RMSE gives the actual magnitude of the error, and R² gives the relative performance of the model. This is the most general combination.
- When the data contains many outliers, focus on MAE。
- During model training and optimization, use MSE as the loss function。
- Never look at only a single metric! Only by combining multiple metrics can you evaluate a model comprehensively.
Code practice: evaluation using Scikit-learn
Now, let us practice with Python and the machine learning library Scikit-learn.
Environment Preparation
Make sure the necessary libraries are installed:
Example
pip
install
numpy scikit-learn matplotlib
Complete example code
Example
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
from
sklearn.
model_selection
import
train_test_split
from
sklearn.
linear_model
import
LinearRegression
from
sklearn.
metrics
import
mean_absolute_error
,
mean_squared_error
,
r2_score
1. Create simulated data
np.
random
.
seed
(
42
)
Ensure consistent results across runs
X
=
2
- np.
random
.
rand
(
100
,
1
)
100 samples, 1 feature, range [0, 2)
y
=
4
3
- X + np.
random
.
randn
(
100
,
1
)
True relationship: y = 4 + 3x + noise
2. Split into training and test sets (80% training, 20% testing)
X_train
,
X_test
,
y_train
,
y_test
=
train_test_split
(
X
,
y
,
test_size
=
0.2
,
random_state
=
42
)
3. Train a simple linear regression model
model
=
LinearRegression
(
)
model.
fit
(
X_train
,
y_train
)
4. Make predictions on the test set
y_pred
=
model.
predict
(
X_test
)
5. Compute all evaluation metrics
mae
=
mean_absolute_error
(
y_test
,
y_pred
)
mse
=
mean_squared_error
(
y_test
,
y_pred
)
rmse
=
np.
sqrt
(
mse
)
or use mean_squared_error(y_test, y_pred, squared=False)
r2
=
r2_score
(
y_test
,
y_pred
)
6. Print the evaluation results
(
"=== Regression Model Evaluation Report ==="
)
(
f
"Mean Absolute Error (MAE): {mae:.4f}"
)
(
f
"Mean Squared Error (MSE): {mse:.4f}"
)
(
f
"Root Mean Squared Error (RMSE): {rmse:.4f}"
)
(
f
"Coefficient of Determination (R² Score): {r2:.4f}"
)
(
"\nModel coefficients:"
)
(
f
" Intercept: {model.intercept_[0]:.4f}"
)
(
f
" Slope (Coefficient for X): {model.coef_[0][0]:.4f}"
)
7. Visualize the results
plt.
figure
(
figsize
=
(
10
,
5
)
)
Subplot 1: scatter plot of true values vs predicted values
plt.
subplot
(
1
,
2
,
1
)
plt.
scatter
(
y_test
,
y_pred
,
alpha
=
0.7
,
edgecolors
=
'k'
)
plt.
plot
(
[
y_test.
min
(
)
,
y_test.
max
(
)
]
,
[
y_test.
min
(
)
,
y_test.
max
(
)
]
,
'r--'
,
lw
=
2
,
label
=
'Perfect prediction line'
)
plt.
xlabel
(
'True values (y_test)'
)
plt.
ylabel
(
'Predicted values (y_pred)'
)
plt.
title
(
'True values vs predicted values'
)
plt.
legend
(
)
plt.
grid
(
True
,
linestyle
=
'--'
,
alpha
=
0.7
)
Subplot 2: histogram of error distribution
plt.
subplot
(
1
,
2
,
2
)
errors
=
y_test.
flatten
(
)
- y_pred.
flatten
(
)
plt.
hist
(
errors
,
bins
=
15
,
edgecolor
=
'black'
,
alpha
=
0.7
)
plt.
axvline
(
x
=
0
,
color
=
'r'
,
linestyle
=
'--'
,
label
=
'Zero-error line'
)
plt.
xlabel
(
'Prediction error'
)
plt.
ylabel
(
'Frequency'
)
plt.
title
(
'Prediction error distribution'
)
plt.
legend
(
)
plt.
grid
(
True
,
linestyle
=
'--'
,
alpha
=
0.7
,
axis
=
'y'
)
plt.
tight_layout
(
)
plt.
show
(
)
Line-by-line code explanation
- Create data: we simulated
y = 4 + 3x + 噪声data, which is a typical linear relationship plus random noise. - Split the dataset:
train_test_splitRandomly split the data into two parts. Use the training set (X_train,y_train) to learn the model, and the never-seen test set (X_test,y_test) to evaluate its generalization ability. This is a key step in evaluation! - Train the model: Creating
LinearRegressionobject and call the.fit()method to train it. - Make predictions: Calling
.predict()method generates predictions for the test set featuresX_testgenerate predicted valuesy_pred。 - Compute metrics: using functions from Scikit-learn's
metricsmetrics module, easily compute MAE, MSE, and R². RMSE is obtained by taking the square root of MSE. - Print the result: format and output all metrics and the parameters learned by the model.
- Visualization:
Practical exercises and summary
Hands-on Exercises
- Run the Code: copy the code above into your Python environment and run it, observing the output results and plots.
- Update data: try increasing the
np.random.randn()noise level in it and rerun. Observe how all the evaluation metrics change and how the plots differ. - Change the model: try using
from sklearn.tree import DecisionTreeRegressorto replace the linear regression model. Compare the evaluation metrics of the two models. - Calculation exercise: manually compute the MAE, MSE, RMSE, and R² for the following three samples.