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:
- Method A (simple split): The teacher randomly picks 10 questions from the question bank for a mock exam, and uses this score to predict your final exam result.
- Method B (cross-validation): The teacher divides the question bank into 5 parts. The first time, train you with parts 2, 3, 4, and 5, and test with part 1; the second time, train with parts 1, 3, 4, and 5, and test with part 2 ... repeating this 5 times. Finally, take the average of the 5 test scores to assess you.
Which method is more reliable? Obviously it isMethod B。
- Method A's risk is: if the 10 questions drawn happen to all be types you are good at, your mock exam score will be inflated, leading to excessive optimism about your true level; conversely, if they are all your blind spots, the score will be too low, leading to excessive pessimism. The evaluation result fluctuates greatly and is unstable.
- Method BThrough multiple different training/testing combinations, you experience all kinds of question types in the bank, and the resulting average score better represents your comprehensive, stable level and predicts the final exam result more accurately.
In machine learning:
- the question bank is ourentire dataset。
- Student is themachine learning model。
- the mock exam score is the model'sEvaluation Metricsevaluation metric (such as accuracy, mean squared error, etc.).
- The final exam is the model's performance on futurereal, unknowndata.
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
]
- X
[
:
,
1
]
0.7
- X
[
:
,
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
)
(
f
"Model accuracy: {accuracy:.4f}"
)
Output result:
模型准确率: 0.8833
Process description:

-
Fixed size, stores elements of the same type. Simple and fast, with low computational cost.
- High efficiency in random access of elements. The evaluation result depends heavily on the single random split. If the split is unfavorable, the result may not be representative. Moreover, because the test set is used only once, data is underutilized.
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
]
- X
[
:
,
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'
)
(
f
"Accuracy per fold: {scores}"
)
(
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?
- Common Values: 5 or 10. This is an empirical trade-off.
- Smaller K (such as 3): larger training set, but fewer evaluations and possibly higher variance in the estimate.
- Larger K (such as 10 or 20): more stable evaluation (lower variance), but each training set is closer to the original dataset, which may introduce a more optimistic estimation bias, and the computational cost increases significantly.
- Extreme case K = N (number of samples): This is leave-one-out, testing with only one sample at a time. The evaluation is the least biased, but the computational cost is extremely high, so it is usually used only for very small datasets.
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
)
:
(
f
"Training set index range: {train_index[0]} to {train_index[-1]}"
)
(
f
"Test set index range: {test_index[0]} to {test_index[-1]}"
)
(
"---"
)
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:
- For each candidate model, use cross-validation on theTraining Settraining set to obtain its performance estimate.
- Compare these average cross-validation scores and select the model with the highest score.
- 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
]
- X
[
:
,
1
]
0.8
- X
[
:
,
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
(
)
(
f
"{name} average accuracy: {scores.mean():.4f}"
)
Select the best model
best_model_name
=
max
(
results
,
key
=
results.
get
)
(
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
)
(
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
- X
[
:
,
1
]
0.4
- X
[
:
,
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
(
f
"Best parameters: {grid_search.best_params_}"
)
(
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
)
(
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
- Basic Implementation: When using
sklearnthe built-in iris dataset, usingtrain_test_splitandcross_val_score(K=5) to train and evaluate aKNeighborsClassifierand compare the scores obtained by the two evaluation methods. - Model ComparisonTask: On the same dataset, use cross-validation to compare the
SVC、RandomForestClassifierandGradientBoostingClassifierperformance of the models. - Parameter tuning: For the
SVCmodel, design a parameter grid (includingCandgamma), and useGridSearchCVto find the optimal parameters.
Summary of Key Points
- Purpose of cross-validation: Obtain a more robust and reliable estimate of the model's generalization ability.
- Core Methods:K-fold cross validationis the gold standard; for classification problems, preferstratified K-fold cross validation。
- Key distinction:
- Training set / validation set: Used for model training andevaluation 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, forthe final one-time performance report. It must be strictly isolated and never used for any decision.
- Engineering role: Cross-validation is the bridge connecting model development (training, parameter tuning) and model evaluation (testing), and the cornerstone for ensuring model quality, preventing overfitting, and achieving reliable model selection and optimization.