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

Overfitting, Underfitting, Bias, and Variance

Overfitting, Underfitting, Bias, and Variance

In the world of machine learning, building a model is like training a student. Our goal is that this student not only memorizes the examples in the textbook (training data) but also deeply understands the underlying principles, so as to achieve good results on brand-new, never-before-seen exam questions (test data). However, during the learning process, this student may encounter two typical problems:

Understand Overfitting The difference between Underfitting, and the deeper theoretical concepts behind them —Bias The difference between Varianceis a key step for every machine learning practitioner from beginner to mastery. They explain why models make mistakes and point out the direction for model improvement.


I. Core Concepts: Model Performance and "Fitting" State

First, let's understand whatfittingis through an intuitive example. Suppose we want to use a mathematical model to fit a set of scatter data.

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

-------------------------- Set Chinese font start --------------------------

plt.

rcParams

[

'font.sans-serif'

]

=

[

   

Windows first

   

'SimHei'

,

'Microsoft YaHei'

,

   

macOS first

   

'PingFang SC'

,

'Heiti TC'

,

   

Linux first

   

'WenQuanYi Micro Hei'

,

'DejaVu Sans'

]

Fix the issue of minus signs displaying as squares

plt.

rcParams

[

'axes.unicode_minus'

]

=

False

-------------------------- Set Chinese font end --------------------------

Generate simulated data: add some random noise on top of a sine curve

np.

random

.

seed

(

42

)

X

=

np.

linspace

(

0

,

10

,

20

)

y_true

=

np.

sin

(

X

)

                   

The true underlying pattern (which we don't know)

y_noise

=

np.

random

.

randn

(

20

)

0.3

 

Random noise

y

=

y_true + y_noise                  

The data we actually observe

plt.

scatter

(

X

,

y

,

label

=

'Observed Data (with Noise)'

,

color

=

'blue'

,

alpha

=

0.6

)

plt.

plot

(

X

,

y_true

,

label

=

'True Pattern (y=sin(x))'

,

color

=

'green'

,

linewidth

=

2

)

plt.

xlabel

(

'X'

)

plt.

ylabel

(

'y'

)

plt.

title

(

'Data and Underlying Pattern'

)

plt.

legend

(

)

plt.

grid

(

True

)

plt.

show

(

)

Our goal is to find a curve (model) that best describes the pattern reflected by these blue scatter points (the data).

The degree to which the model describes the data isfitting。

1. Underfitting

Underfitting refers to a model that is too simple to capture the basic patterns or regularities in the data. It is like a student who has only learned addition but is asked to solve calculus problems.

Example

from

sklearn.

linear_model

import

LinearRegression

from

sklearn.

preprocessing

import

PolynomialFeatures

from

sklearn.

metrics

import

mean_squared_error

Try fitting with a degree-1 polynomial (straight line)

poly

=

PolynomialFeatures

(

degree

=

1

)

X_poly1

=

poly.

fit_transform

(

X.

reshape

(

1

,

1

)

)

model_under

=

LinearRegression

(

)

model_under.

fit

(

X_poly1

,

y

)

y_pred_under

=

model_under.

predict

(

X_poly1

)

mse_train_under

=

mean_squared_error

(

y

,

y_pred_under

)

print

(

f

"Mean squared error (MSE) of the underfitting model on the training set: {mse_train_under:.4f}"

)

Output:

欠拟合模型在训练集上的均方误差 (MSE): 0.4402

欠拟合模型在训练集上的均方误差 (MSE): 0.4402

2. Just-Right Fitting

This is the ideal state. The model is complex enough to learn the key patterns in the data, but not so complex that it learns the random noise. It performs well on both the training set and the unseen test set.

Example

Try fitting with a degree-3 polynomial

poly

=

PolynomialFeatures

(

degree

=

3

)

X_poly3

=

poly.

fit_transform

(

X.

reshape

(

1

,

1

)

)

model_good

=

LinearRegression

(

)

model_good.

fit

(

X_poly3

,

y

)

y_pred_good

=

model_good.

predict

(

X_poly3

)

mse_train_good

=

mean_squared_error

(

y

,

y_pred_good

)

print

(

f

"Mean squared error (MSE) of the well-fitting model on the training set: {mse_train_good:.4f}"

)

Output:



欠拟合模型在训练集上的均方误差 (MSE): 0.4402

良好拟合模型在训练集上的均方误差 (MSE): 0.3988

3. Overfitting

Overfitting refers to a model that is too complex, learning not only the true patterns in the data but also "memorizing" the random noise and outliers in the training data.

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn.

linear_model

import

LinearRegression

from

sklearn.

preprocessing

import

PolynomialFeatures

from

sklearn.

metrics

import

mean_squared_error

-------------------------- Set Chinese font start --------------------------

plt.

rcParams

[

'font.sans-serif'

]

=

[

   

Windows first

   

'SimHei'

,

'Microsoft YaHei'

,

   

macOS first

   

'PingFang SC'

,

'Heiti TC'

,

   

Linux first

   

'WenQuanYi Micro Hei'

,

'DejaVu Sans'

]

Fix the issue of minus signs displaying as squares

plt.

rcParams

[

'axes.unicode_minus'

]

=

False

-------------------------- Set Chinese font end --------------------------

Generate simulated data: add some random noise on top of a sine curve

np.

random

.

seed

(

42

)

X

=

np.

linspace

(

0

,

10

,

20

)

y_true

=

np.

sin

(

X

)

                   

The true underlying pattern (which we don't know)

y_noise

=

np.

random

.

randn

(

20

)

0.3

 

Random noise

y

=

y_true + y_noise                  

The data we actually observe

Try fitting with a degree-1 polynomial (straight line)

poly

=

PolynomialFeatures

(

degree

=

1

)

X_poly1

=

poly.

fit_transform

(

X.

reshape

(

1

,

1

)

)

model_under

=

LinearRegression

(

)

model_under.

fit

(

X_poly1

,

y

)

y_pred_under

=

model_under.

predict

(

X_poly1

)

mse_train_under

=

mean_squared_error

(

y

,

y_pred_under

)

print

(

f

"Mean squared error (MSE) of the underfitting model on the training set: {mse_train_under:.4f}"

)

Try fitting with a degree-3 polynomial

poly

=

PolynomialFeatures

(

degree

=

3

)

X_poly3

=

poly.

fit_transform

(

X.

reshape

(

1

,

1

)

)

model_good

=

LinearRegression

(

)

model_good.

fit

(

X_poly3

,

y

)

y_pred_good

=

model_good.

predict

(

X_poly3

)

mse_train_good

=

mean_squared_error

(

y

,

y_pred_good

)

print

(

f

"Mean squared error (MSE) of the well-fitting model on the training set: {mse_train_good:.4f}"

)

Try fitting with a degree-15 polynomial (very prone to overfitting)

poly

=

PolynomialFeatures

(

degree

=

15

)

X_poly15

=

poly.

fit_transform

(

X.

reshape

(

1

,

1

)

)

model_over

=

LinearRegression

(

)

model_over.

fit

(

X_poly15

,

y

)

y_pred_over

=

model_over.

predict

(

X_poly15

)

mse_train_over

=

mean_squared_error

(

y

,

y_pred_over

)

print

(

f

"Mean squared error (MSE) of the overfitting model on the training set: {mse_train_over:.4f}"

)

Visualize the three fitting states

plt.

figure

(

figsize

=

(

15

,

4

)

)

Underfitting

plt.

subplot

(

1

,

3

,

1

)

plt.

scatter

(

X

,

y

,

alpha

=

0.6

)

plt.

plot

(

X

,

y_pred_under

,

color

=

'red'

,

linewidth

=

2

,

label

=

'Underfitting (Degree 1)'

)

plt.

plot

(

X

,

y_true

,

color

=

'green'

,

linestyle

=

'--'

,

label

=

'True Pattern'

)

plt.

title

(

f

'Underfitting\nTraining MSE: {mse_train_under:.4f}'

)

plt.

legend

(

)

plt.

grid

(

True

)

Good fit

plt.

subplot

(

1

,

3

,

2

)

plt.

scatter

(

X

,

y

,

alpha

=

0.6

)

plt.

plot

(

X

,

y_pred_good

,

color

=

'red'

,

linewidth

=

2

,

label

=

'Good Fit (Degree 3)'

)

plt.

plot

(

X

,

y_true

,

color

=

'green'

,

linestyle

=

'--'

,

label

=

'True Pattern'

)

plt.

title

(

f

'Good Fit\nTraining MSE: {mse_train_good:.4f}'

)

plt.

legend

(

)

plt.

grid

(

True

)

Overfitting

plt.

subplot

(

1

,

3

,

3

)

plt.

scatter

(

X

,

y

,

alpha

=

0.6

)

plt.

plot

(

X

,

y_pred_over

,

color

=

'red'

,

linewidth

=

2

,

label

=

'Overfitting (Degree 15)'

)

plt.

plot

(

X

,

y_true

,

color

=

'green'

,

linestyle

=

'--'

,

label

=

'True Pattern'

)

plt.

title

(

f

'Overfitting\nTraining MSE: {mse_train_over:.4f}'

)

plt.

legend

(

)

plt.

grid

(

True

)

plt.

tight_layout

(

)

plt.

show

(

)

We can clearly see from the figure:


II. Theoretical Foundation: Bias-Variance Decomposition

Bias and variance provide a theoretical framework for understanding overfitting and underfitting. They describe two different sources of model error.

We can decompose the model'stotal errorinto:Bias² + Variance + Irreducible Error。

1. Bias

2. Variance

3. The Bias-Variance Tradeoff

This is a core tradeoff in machine learning.We cannot minimize bias and variance at the same time.

Our goal is to find the "sweet spot" in the figure that minimizes the total error.


III. Diagnosis and Coping Strategies

How do you tell which state the model is in? How do you fix it?

1. Diagnostic Method: Learning Curves

A learning curve plots the model'sTraining Setandvalidation setperformance (such as error) on thenumber of training samplesormodel complexityagainst.

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn.

datasets

import

load_diabetes

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

model_selection

import

learning_curve

from

sklearn.

pipeline

import

make_pipeline

from

sklearn.

linear_model

import

LinearRegression

from

sklearn.

preprocessing

import

PolynomialFeatures

,

StandardScaler

from

sklearn.

metrics

import

mean_squared_error

import

warnings

warnings

.

filterwarnings

(

'ignore'

)

-------------------------- Set Chinese font start --------------------------

plt.

rcParams

[

'font.sans-serif'

]

=

[

   

Windows first

   

'SimHei'

,

'Microsoft YaHei'

,

   

macOS first

   

'PingFang SC'

,

'Heiti TC'

,

   

Linux first

   

'WenQuanYi Micro Hei'

,

'DejaVu Sans'

]

Fix the issue of minus signs displaying as squares

plt.

rcParams

[

'axes.unicode_minus'

]

=

False

Set chart style

plt.

rcParams

[

'figure.figsize'

]

=

(

10

,

6

)

plt.

rcParams

[

'axes.grid'

]

=

True

plt.

rcParams

[

'grid.alpha'

]

=

0.3

-------------------------- Set Chinese font end --------------------------

Load data

data

=

load_diabetes

(

)

X

,

y

=

data.

data

,

data.

target

Use only one feature (more suitable for polynomial regression demonstration)

X

=

X

[

:

,

np.

newaxis

,

2

]

 

Select the third feature (BMI)

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.2

,

random_state

=

42

)

Define the learning curve plotting function (optimized version)

def

plot_learning_curve

(

estimator

,

title

,

X

,

y

,

cv

=

5

,

train_sizes

=

np.

linspace

(

0.1

,

1.0

,

10

)

)

:

   

"""
    Plot the learning curve
    Parameters:
        estimator: model estimator
        title: chart title
        X: feature data
        y: target variable
        cv: number of cross-validation folds
        train_sizes: proportion of training samples
    """

   

Get learning curve data

    train_sizes_abs

,

train_scores

,

test_scores

=

learning_curve

(

        estimator

,

X

,

y

,

cv

=

cv

,

scoring

=

'neg_mean_squared_error'

,

        train_sizes

=

train_sizes

,

random_state

=

42

,

n_jobs

=

1

   

)

   

   

Compute the mean and standard deviation

    train_scores_mean

=

-train_scores.

mean

(

axis

=

1

)

    train_scores_std

=

train_scores.

std

(

axis

=

1

)

    test_scores_mean

=

-test_scores.

mean

(

axis

=

1

)

    test_scores_std

=

test_scores.

std

(

axis

=

1

)

   

   

Plot the learning curve

    plt.

figure

(

figsize

=

(

10

,

6

)

)

    plt.

fill_between

(

train_sizes_abs

,

                     train_scores_mean - train_scores_std

,

                     train_scores_mean + train_scores_std

,

                     alpha

=

0.1

,

color

=

'r'

)

    plt.

fill_between

(

train_sizes_abs

,

                     test_scores_mean - test_scores_std

,

                     test_scores_mean + test_scores_std

,

                     alpha

=

0.1

,

color

=

'g'

)

   

   

Plot the mean curve

    plt.

plot

(

train_sizes_abs

,

train_scores_mean

,

'o-'

,

color

=

'r'

,

linewidth

=

2

,

             markersize

=

8

,

label

=

'Training Set MSE'

)

    plt.

plot

(

train_sizes_abs

,

test_scores_mean

,

'o-'

,

color

=

'g'

,

linewidth

=

2

,

             markersize

=

8

,

label

=

'Validation Set MSE'

)

   

   

Set chart properties

    plt.

xlabel

(

'Number of Training Samples'

,

fontsize

=

12

)

    plt.

ylabel

(

'Mean Squared Error (MSE)'

,

fontsize

=

12

)

    plt.

title

(

title

,

fontsize

=

14

,

pad

=

20

)

    plt.

legend

(

loc

=

'upper right'

,

fontsize

=

11

)

    plt.

tight_layout

(

)

    plt.

show

(

)

   

   

Print the model's performance on the test set

    estimator.

fit

(

X_train

,

y_train

)

    y_pred

=

estimator.

predict

(

X_test

)

    mse

=

mean_squared_error

(

y_test

,

y_pred

)

   

print

(

f

"{title} - Test Set MSE: {mse:.2f}"

)

1. Underfitting Model (1st-degree polynomial - linear regression)

print

(

"="

60

)

print

(

"Underfitting Model (1st-degree polynomial - linear regression)"

)

print

(

"="

60

)

plot_learning_curve

(

    make_pipeline

(

StandardScaler

(

)

,

PolynomialFeatures

(

1

)

,

LinearRegression

(

)

)

,

   

'Underfitting Model Learning Curve (1st-degree polynomial)'

,

    X

,

y

)

2. Well-Fitting Model (2nd-degree polynomial)

print

(

"\n"

"="

60

)

print

(

"Well-Fitting Model (2nd-degree polynomial)"

)

print

(

"="

60

)

plot_learning_curve

(

    make_pipeline

(

StandardScaler

(

)

,

PolynomialFeatures

(

2

)

,

LinearRegression

(

)

)

,

   

'Well-Fitting Model Learning Curve (2nd-degree polynomial)'

,

    X

,

y

)

3. Overfitting Model (8th-degree polynomial)

print

(

"\n"

"="

60

)

print

(

"Overfitting Model (8th-degree polynomial)"

)

print

(

"="

60

)

plot_learning_curve

(

    make_pipeline

(

StandardScaler

(

)

,

PolynomialFeatures

(

8

)

,

LinearRegression

(

)

)

,

   

'Overfitting Model Learning Curve (8th-degree polynomial)'

,

    X

,

y

)

Extra: Visualize the fitting effect of models of different degrees

plt.

figure

(

figsize

=

(

12

,

8

)

)

X_plot

=

np.

linspace

(

X.

min

(

)

,

X.

max

(

)

,

100

)

.

reshape

(

1

,

1

)

Plot the original data points

plt.

scatter

(

X_train

,

y_train

,

alpha

=

0.5

,

label

=

'Training data'

,

color

=

'blue'

,

s

=

30

)

plt.

scatter

(

X_test

,

y_test

,

alpha

=

0.5

,

label

=

'Test Data'

,

color

=

'orange'

,

s

=

30

)

Plot fitting curves of different degrees

orders

=

[

1

,

2

,

8

]

colors

=

[

'red'

,

'green'

,

'purple'

]

labels

=

[

'1st Degree (Underfitting)'

,

'2nd Degree (Well-Fitting)'

,

'8th Degree (Overfitting)'

]

for

i

,

order

in

enumerate

(

orders

)

:

    model

=

make_pipeline

(

StandardScaler

(

)

,

PolynomialFeatures

(

order

)

,

LinearRegression

(

)

)

    model.

fit

(

X_train

,

y_train

)

    y_plot

=

model.

predict

(

X_plot

)

    plt.

plot

(

X_plot

,

y_plot

,

color

=

colors

[

i

]

,

linewidth

=

2

,

label

=

labels

[

i

]

)

plt.

xlabel

(

'BMI Feature (Standardized)'

,

fontsize

=

12

)

plt.

ylabel

(

'Diabetes Progression Measure'

,

fontsize

=

12

)

plt.

title

(

'Comparison of Fitting Effects of Polynomial Regression with Different Degrees'

,

fontsize

=

14

,

pad

=

20

)

plt.

legend

(

fontsize

=

11

)

plt.

tight_layout

(

)

plt.

show

(

)

How to interpret learning curves?

Fitting State Training Error Validation Error Curve Characteristics
Underfitting High High Both curves are high and very close; adding more data does not help.
Good fit Low Low Both curves are low and close to each other, reaching a balance point.
Overfitting Very low High The training error is very low but the validation error is high, with a clear gap between them. Adding more data usually brings them closer.

2. Coping Strategies

Based on the diagnosis, we can adopt different strategies:

To address underfitting (high bias):

To address overfitting (high variance):

- **L1 Regularization (Lasso)**: tends to produce sparse weights and can be used for feature selection. - **L2 Regularization (Ridge)**: causes weights to decay, tending to keep all weights small. - **Dropout** (for neural networks): randomly "drops out" a portion of neurons during training.

IV. Practical Exercise: Experiencing on a Real Dataset

Let's practice on the classic Boston housing dataset (or the diabetes dataset, since the Boston dataset has been deprecated).

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn.

datasets

import

load_diabetes

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

tree

import

DecisionTreeRegressor

from

sklearn.

metrics

import

mean_squared_error

-------------------------- Set Chinese font start --------------------------

plt.

rcParams

[

'font.sans-serif'

]

=

[

   

Windows first

   

'SimHei'

,

'Microsoft YaHei'

,

   

macOS first

   

'PingFang SC'

,

'Heiti TC'

,

   

Linux first

   

'WenQuanYi Micro Hei'

,

'DejaVu Sans'

]

Fix the issue of minus signs displaying as squares

plt.

rcParams

[

'axes.unicode_minus'

]

=

False

-------------------------- Set Chinese font end --------------------------

Load data

data

=

load_diabetes

(

)

X

,

y

=

data.

data

,

data.

target

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.2

,

random_state

=

42

)

Try decision trees of different complexity

max_depths

=

[

1

,

3

,

10

,

None

]

 

None means no depth limit; the tree keeps growing until it is "pure"

train_errors

=

[

]

test_errors

=

[

]

for

depth

in

max_depths:

    model

=

DecisionTreeRegressor

(

max_depth

=

depth

,

random_state

=

42

)

    model.

fit

(

X_train

,

y_train

)

    y_train_pred

=

model.

predict

(

X_train

)

    y_test_pred

=

model.

predict

(

X_test

)

    train_error

=

mean_squared_error

(

y_train

,

y_train_pred

)

    test_error

=

mean_squared_error

(

y_test

,

y_test_pred

)

    train_errors.

append

(

train_error

)

    test_errors.

append

(

test_error

)

   

print

(

f

"Max tree depth: {depth if depth is not None else 'unlimited'}"

)

   

print

(

f

" Training Set MSE: {train_error:.2f}"

)

   

print

(

f

" Test Set MSE: {test_error:.2f}"

)

   

print

(

"-"

30

)

Visualization

plt.

figure

(

figsize

=

(

10

,

6

)

)

depths

=

[

str

(

d

)

if

d

else

'Unlimited'

for

d

in

max_depths

]

x_index

=

np.

arange

(

len

(

depths

)

)

width

=

0.35

plt.

bar

(

x_index - width/

2

,

train_errors

,

width

,

label

=

'Training Error'

,

color

=

'skyblue'

)

plt.

bar

(

x_index + width/

2

,

test_errors

,

width

,

label

=

'Test Error'

,

color

=

'lightcoral'

)

plt.

xlabel

(

'Max Decision Tree Depth (Model Complexity)'

)

plt.

ylabel

(

'Mean Squared Error (MSE)'

)

plt.

title

(

'Bias-Variance Tradeoff: Performance of Decision Trees with Different Complexity'

)

plt.

xticks

(

x_index

,

depths

)

plt.

legend

(

)

plt.

grid

(

True

,

axis

=

'y'

)

plt.

tight_layout

(

)

plt.

show

(

)

Analyze the results:

Summary

Understanding overfitting, underfitting, bias, and variance is the cornerstone of building excellent machine learning models. Remember this core loop:

  1. Train the model -> Evaluate its performance on the training and validation sets。
  2. Diagnose the problem through learning curves or error comparison: Is it high bias (underfitting) or high variance (overfitting)?
  3. Apply the corresponding strategy(increase complexity/data, regularization, etc.) to improve.
  4. Go back to step 1until you obtain a satisfactory model with strong generalization ability on the validation set.