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

Cross-validation

Cross-validation

In the practice of machine learning, we often face a core question: how do we evaluate whether a model is good? You might think of training the model on one portion of data and then testing its performance on another portion it has not seen. This idea is completely correct, but how exactly can we evaluate a model more reliably and stably? This is the Cross-validation core problem that cross-validation aims to solve.

Simply put, cross-validation is a statistical method that evaluates a model's generalization ability (i.e., its ability to handle new data) by repeatedly partitioning the dataset. It is like arranging a mock exam for the model, using multiple different sets of mock test papers (data subsets) to check its true level, avoiding misjudgment due to the chance factors of a single exam.

This article will help you deeply understand the principles of cross-validation, its common methods, and its key role in model optimization and engineering.


Why Do We Need Cross-Validation?

Before diving into technical details, let us understand its necessity through an analogy.

Imagine you are a student about to take an important math exam. There are two ways to assess your level:

Which method is more reliable? Obviously it isMethod B。

In machine learning:

The core goal of cross-validation is to provide amore robust and less biased estimateof the model's generalization ability, thereby helping us perform more reliable model selection, parameter tuning, and performance evaluation.


Common Methods of Cross-Validation

Cross-validation has many implementations suited to different data and scenarios; the most commonly used ones are introduced below.

1. Hold-Out Method (Hold-Out Validation)

This is the simplest and most intuitive method.

Example

import

numpy

as

np

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

ensemble

import

RandomForestClassifier

from

sklearn.

metrics

import

accuracy_score

Construct runnable data

200 samples, 4 features, binary classification

np.

random

.

seed

(

42

)

X

=

np.

random

.

randn

(

200

,

4

)

y

=

(

X

[

:

,

0

]

[

:

,

1

]

0.7

[

:

,

2

]

0.4

0

)

.

astype

(

int

)

1. Split into training and test sets (7:3)

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

    X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

2. Train the model

model

=

RandomForestClassifier

(

random_state

=

42

)

model.

fit

(

X_train

,

y_train

)

3. Evaluate on the test set

y_pred

=

model.

predict

(

X_test

)

accuracy

=

accuracy_score

(

y_test

,

y_pred

)

print

(

f

"Model accuracy: {accuracy:.4f}"

)

Output result:

模型准确率: 0.8833

Process description:

2. K-Fold Cross Validation

This is currently the most commonly used and standard cross-validation method.

Principle: Randomly andevenlydivide the dataset into K mutually exclusive subsets (called folds or Folds).

In each experiment, one subset is taken in turn as the test set and the remaining K-1 subsets as the training set. This process is repeated K times, ensuring each subset is used as the test set once. Finally, we obtain K evaluation scores and take their average as the final performance estimate of the model.

Example

import

numpy

as

np

from

sklearn.

model_selection

import

cross_val_score

,

KFold

from

sklearn.

linear_model

import

LogisticRegression

Construct runnable example data

100 samples, 4 features, binary classification labels

np.

random

.

seed

(

42

)

X

=

np.

random

.

randn

(

100

,

4

)

y

=

(

X

[

:

,

0

]

[

:

,

1

]

0.5

0

)

.

astype

(

int

)

1. Initialize the model

model

=

LogisticRegression

(

max_iter

=

1000

)

2. Define the K-fold cross-validation splitter (K=5)

kfold

=

KFold

(

n_splits

=

5

,

shuffle

=

True

,

random_state

=

42

)

3. Perform cross-validation

scores

=

cross_val_score

(

model

,

X

,

y

,

cv

=

kfold

,

scoring

=

'accuracy'

)

print

(

f

"Accuracy per fold: {scores}"

)

print

(

f

"Average accuracy: {scores.mean():.4f} (+/- {scores.std() * 2:.4f})"

)

每次折叠的准确率: [0.9  0.95 1.   0.95 1.  ]

平均准确率: 0.9600 (+/- 0.0748)

Flow diagram when K=5:

How to choose the value of K?

Fixed size, stores elements of the same type. Data is fully utilized, and the evaluation result is stable and reliable.

High efficiency in random access of elements. The computational cost is K times that of the hold-out method.

3. Stratified K-Fold Cross Validation

This is an important variant of K-fold cross validation, especially suitable forClassification problemsMediumimbalanced class distributionsdatasets.

Problem solved: In ordinary K-fold cross validation, random splitting may cause the proportion of a certain class in some folds to differ greatly from the original dataset. For example, in a dataset with 90% positive and 10% negative samples, randomly splitting into 5 folds may result in one fold containing all positives and no negatives, making the evaluation on that fold meaningless.

When splitting, stratified K-fold cross validation ensures that the proportion of each class in every fold stays consistent with the overall proportion in the original dataset.

Example

from

sklearn.

model_selection

import

StratifiedKFold

,

cross_val_score

Usage is almost the same as KFold; just replace the splitter

stratified_kfold

=

StratifiedKFold

(

n_splits

=

5

,

shuffle

=

True

,

random_state

=

42

)

scores

=

cross_val_score

(

model

,

X

,

y

,

cv

=

stratified_kfold

,

scoring

=

'accuracy'

)

For classification tasks, especially when classes are imbalanced,Priority use StratifiedKFold。

4. Time Series Split (Time Series Cross Validation)

ForFor time series data,the order of data is crucial (tomorrow's data depends on today's and yesterday's). We cannot shuffle the data randomly; we must preserve the temporal order.

Its principle is: the training set always consists of earlier data in time, and the test set is the data immediately following it. As the number of folds increases, the training set window keeps expanding.

Example

import

numpy

as

np

from

sklearn.

model_selection

import

TimeSeriesSplit

Construct runnable time series data

100 time points, 2 features

np.

random

.

seed

(

42

)

X

=

np.

random

.

randn

(

100

,

2

)

TimeSeriesSplit example

tscv

=

TimeSeriesSplit

(

n_splits

=

5

)

for

train_index

,

test_index

in

tscv.

split

(

X

)

:

   

print

(

f

"Training set index range: {train_index[0]} to {train_index[-1]}"

)

   

print

(

f

"Test set index range: {test_index[0]} to {test_index[-1]}"

)

   

print

(

"---"

)

Output:

训练集索引范围: 0 到 19

测试集索引范围: 20 到 35

---

训练集索引范围: 0 到 35

测试集索引范围: 36 到 51

---

训练集索引范围: 0 到 51

测试集索引范围: 52 到 67

---

训练集索引范围: 0 到 67

测试集索引范围: 68 到 83

---

训练集索引范围: 0 到 83

测试集索引范围: 84 到 99

---


Applications of Cross-Validation in Model Engineering

Cross-validation is not only an evaluation tool, but also a core link in the model optimization and engineering workflow.

Application 1: Model Selection and Comparison

When we need to choose one from multiple candidate models (such as linear regression, decision trees, and support vector machines), we cannot use the test set to choose (otherwise the test set becomes part of the training process and "leaks" information). The correct approach is:

  1. For each candidate model, use cross-validation on theTraining Settraining set to obtain its performance estimate.
  2. Compare these average cross-validation scores and select the model with the highest score.
  3. Finally,retrain this selected model on the entire training set, and use theindependent test setfor a final one-time evaluation, reporting this score as the model's final performance.

Example

import

numpy

as

np

from

sklearn.

model_selection

import

cross_val_score

,

StratifiedKFold

,

train_test_split

from

sklearn.

linear_model

import

LogisticRegression

from

sklearn.

svm

import

SVC

from

sklearn.

tree

import

DecisionTreeClassifier

Construct runnable classification data

200 samples, 4 features, binary classification

np.

random

.

seed

(

42

)

X

=

np.

random

.

randn

(

200

,

4

)

y

=

(

X

[

:

,

0

]

[

:

,

1

]

0.8

[

:

,

2

]

0.3

0

)

.

astype

(

int

)

Split training set / test set

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

    X

,

y

,

test_size

=

0.25

,

random_state

=

42

,

stratify

=

y

)

Define the model

models

=

{

   

'Logistic Regression'

: LogisticRegression

(

max_iter

=

1000

)

,

   

'SVM'

: SVC

(

)

,

   

'Decision Tree'

: DecisionTreeClassifier

(

)

}

Stratified K-fold cross validation

cv

=

StratifiedKFold

(

n_splits

=

5

,

shuffle

=

True

,

random_state

=

42

)

results

=

{

}

Cross-validation evaluation

for

name

,

model

in

models.

items

(

)

:

    scores

=

cross_val_score

(

model

,

X_train

,

y_train

,

cv

=

cv

,

scoring

=

'accuracy'

)

    results

[

name

]

=

scores.

mean

(

)

   

print

(

f

"{name} average accuracy: {scores.mean():.4f}"

)

Select the best model

best_model_name

=

max

(

results

,

key

=

results.

get

)

print

(

f

"\nAccording to cross-validation, the best model is: {best_model_name}"

)

Final training and test set evaluation

best_model

=

models

[

best_model_name

]

best_model.

fit

(

X_train

,

y_train

)

final_score

=

best_model.

score

(

X_test

,

y_test

)

print

(

f

"Final accuracy of the best model on the independent test set: {final_score:.4f}"

)

Output:

Logistic Regression 平均准确率: 0.9533

SVM 平均准确率: 0.9400

Decision Tree 平均准确率: 0.8467



根据交叉验证,最佳模型是: Logistic Regression

最佳模型在独立测试集上的最终准确率: 1.0000

Application 2: Hyperparameter Tuning

Hyperparameters are parameters that need to be set before model training (such as the number of trees in a random forest n_estimators, and the penalty coefficient in SVM C). The process of finding the best hyperparameter combination is calledHyperparameter tuninggrid search, and cross-validation is its standard evaluation method.

The most commonly used method is Grid Search Cross Validation。

Example

import

numpy

as

np

from

sklearn.

model_selection

import

GridSearchCV

,

train_test_split

from

sklearn.

ensemble

import

RandomForestClassifier

Construct runnable classification data

300 samples, 5 features, binary classification

np.

random

.

seed

(

42

)

X

=

np.

random

.

randn

(

300

,

5

)

y

=

(

X

[

:

,

0

]

0.6

[

:

,

1

]

0.4

[

:

,

2

]

0

)

.

astype

(

int

)

Split training set / test set

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

    X

,

y

,

test_size

=

0.25

,

random_state

=

42

,

stratify

=

y

)

1. Parameter grid

param_grid

=

{

   

'n_estimators'

:

[

50

,

100

,

200

]

,

   

'max_depth'

:

[

None

,

10

,

20

]

,

   

'min_samples_split'

:

[

2

,

5

,

10

]

}

2. Base model

rf

=

RandomForestClassifier

(

random_state

=

42

)

3. GridSearchCV

grid_search

=

GridSearchCV

(

    estimator

=

rf

,

    param_grid

=

param_grid

,

    cv

=

5

,

    scoring

=

'accuracy'

,

    n_jobs

=

1

)

4. Grid search (training set only)

grid_search.

fit

(

X_train

,

y_train

)

5. Optimal parameters and score

print

(

f

"Best parameters: {grid_search.best_params_}"

)

print

(

f

"Best cross-validation score: {grid_search.best_score_:.4f}"

)

6. Test set evaluation

best_rf_model

=

grid_search.

best_estimator_

test_accuracy

=

best_rf_model.

score

(

X_test

,

y_test

)

print

(

f

"Accuracy of the tuned model on the test set: {test_accuracy:.4f}"

)

Output:



最佳参数: {'max_depth': None, 'min_samples_split': 2, 'n_estimators': 100}

最佳交叉验证分数: 0.9067

调优后模型在测试集上的准确率: 0.9467

Key points: GridSearchCV Cross-validation is already performed internally. It further splits the training set X_train into smaller "training subsets" and "validation subsets" to evaluate parameters, so the training set we pass in X_train is equivalent to the entire "question bank," while the test set X_test is the "ultimate exam question" that never takes part in the tuning process, used only for final verification.


Practical exercises and summary

Hands-on Exercises

  1. Basic Implementation: When using sklearn the built-in iris dataset, using train_test_split and cross_val_score (K=5) to train and evaluate a KNeighborsClassifierand compare the scores obtained by the two evaluation methods.
  2. Model ComparisonTask: On the same dataset, use cross-validation to compare the SVC、RandomForestClassifier and GradientBoostingClassifier performance of the models.
  3. Parameter tuning: For the SVC model, design a parameter grid (including C and gamma), and use GridSearchCV to find the optimal parameters.

Summary of Key Points

- **Training set / validation set**: Used for model training and **evaluation during the development process** (such as model selection and parameter tuning). Cross-validation takes place at this stage. - **Test set**: Used only after all development is complete, for **the final one-time performance report**. It must be strictly isolated and never used for any decision.