Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Regression Model Evaluation

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。

Why is evaluation needed?

  1. Model selection: to compare which of different algorithms (such as linear regression and decision tree regression) performs better on your data.
  2. Parameter tuning: when tuning model parameters (such as regularization strength), an objective criterion is needed to judge whether the adjustment is effective.
  3. 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).


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:

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:

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:

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)。

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:

- `R² = 1`: perfect prediction. - `R² = 0`: the model performs the same as predicting with the average. - `R² < 0`: the model performs worse than predicting with the average (indicating the model is completely unsuitable for the data).

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:

  1. 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.
  2. When the data contains many outliers, focus on MAE。
  3. During model training and optimization, use MSE as the loss function。
  4. 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

random

.

rand

(

100

,

1

)

100 samples, 1 feature, range [0, 2)

y

=

4

3

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

print

(

"=== Regression Model Evaluation Report ==="

)

print

(

f

"Mean Absolute Error (MAE): {mae:.4f}"

)

print

(

f

"Mean Squared Error (MSE): {mse:.4f}"

)

print

(

f

"Root Mean Squared Error (RMSE): {rmse:.4f}"

)

print

(

f

"Coefficient of Determination (R² Score): {r2:.4f}"

)

print

(

"\nModel coefficients:"

)

print

(

f

" Intercept: {model.intercept_[0]:.4f}"

)

print

(

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

(

)

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

  1. Create data: we simulated y = 4 + 3x + 噪声 data, which is a typical linear relationship plus random noise.
  2. Split the dataset:train_test_split Randomly 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!
  3. Train the model: Creating LinearRegression object and call the .fit() method to train it.
  4. Make predictions: Calling .predict() method generates predictions for the test set features X_test generate predicted values y_pred。
  5. Compute metrics: using functions from Scikit-learn's metrics metrics module, easily compute MAE, MSE, and R². RMSE is obtained by taking the square root of MSE.
  6. Print the result: format and output all metrics and the parameters learned by the model.
  7. Visualization:
  8. Left plot: ideally, the scatter points should cluster tightly around the red dashed line (the perfect prediction line).
  9. Right plot: the error distribution histogram should be roughly centered at 0 in a normal distribution, which is usually a good sign.
  10. - **Left plot**: ideally, the scatter points should cluster tightly around the red dashed line (the perfect prediction line). - **Right plot**: the error distribution histogram should be roughly centered at 0 in a normal distribution, which is usually a good sign.

    Practical exercises and summary

    Hands-on Exercises

    1. Run the Code: copy the code above into your Python environment and run it, observing the output results and plots.
    2. 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.
    3. Change the model: try using from sklearn.tree import DecisionTreeRegressor to replace the linear regression model. Compare the evaluation metrics of the two models.
    4. Calculation exercise: manually compute the MAE, MSE, RMSE, and R² for the following three samples.
    5. True values y: [10, 20, 30]
    6. Predicted values ŷ: [12, 18, 28]
    7. - True values y: [10, 20, 30] - Predicted values ŷ: [12, 18, 28]