Train-Test Split
In the world of machine learning, data is the fuel that drives all models; however, how correctly to use this fuel determines whether your model is an intelligent engine that accurately predicts the future or a mere parrot that only memorizes by rote.
Today, we will delve into a crucial and fundamental concept in machine learning:the split between training and test sets. This is the first step in building any reliable model, and the key to evaluating a model's true capability.
Simply put, splitting training and test sets is like studying and taking exams in school:
- Training Set is the student's textbooks and exercises; the model uses it to learn the rules and patterns in the data.
- Test Set is the final exam; the model uses it to check whether it has truly mastered the knowledge, rather than merely memorizing the answers to the exercises (training set).
Why must we split training and test sets?
Imagine a student who only reviewed the mock questions given by the teacher, and the exam questions are exactly the same mock questions, and he gets a perfect score. Does this prove he truly understood the subject? Obviously not. He may have simply memorized the answers.
In machine learning, if we train a model onall the dataand then use thissame datato evaluate its performance, we make the same mistake. The model will perform exceptionally well because it has already "seen" and "memorized" all the details of the data, including the noise and accidental patterns. This phenomenon is calledOverfitting。
an overfitted model is like a student who can only recite example problems; once faced with new, unseen questions (new data), it performs poorly. Its "generalization ability" is weak.
Therefore, we must split the data into two parts:
- Training Set: used to teach the model, letting it learn.
- Test Set: used to test the model, evaluating its ability to handlenew data it has never seen.
The test set must be completely isolated from the training set and, throughout the entire model training process, mustNonever be seen by the model. Only in this way can the evaluation results on the test set objectively reflect the model's true generalization ability.
How to split: common methods and strategies
Splitting data sounds simple, but there is quite some knowledge involved. Different splitting strategies suit different scenarios.
1. Simple random split
This is the most basic and commonly used method. Randomly shuffle the entire dataset, then split it into two parts by a certain ratio.
Example
Example: random splitting using Python's scikit-learn library
from
sklearn.
model_selection
import
train_test_split
Assume X is the feature data and y is the label data
X_train
,
X_test
,
y_train
,
y_test
=
train_test_split
(
X
,
y
,
test_size
=
0.2
,
random_state
=
42
)
(
f
"Number of training set samples: {len(X_train)}"
)
(
f
"Number of test set samples: {len(X_test)}"
)
Code Analysis:
train_test_split: this is the core function in scikit-learn for splitting data.X, y: the input feature data and corresponding labels.test_size=0.2: specifies the size ratio of the test set as 20% (i.e., the training set is 80%). You can also usetrain_size=0.8to specify it.random_state=42: sets a random seed. This ensures that each time you run the code, the split result is completely identical, which is crucial for the reproducibility of experiments. You can set it to any integer.
2. Stratified sampling split
In classification problems, if the class distribution of the dataset is imbalanced (e.g., 90% class A, 10% class B), simple random splitting may cause large differences in the proportions of each class between the training and test sets, affecting the fairness of the evaluation.
Stratified samplingcan ensure that, in the split training and test sets, the proportion of each class remains consistent with the original dataset.
Example
Example: using stratified sampling in a classification problem
from
sklearn.
model_selection
import
train_test_split
Assume y is the classification label
X_train
,
X_test
,
y_train
,
y_test
=
train_test_split
(
X
,
y
,
test_size
=
0.2
,
stratify
=
y
,
random_state
=
42
)
Check the class proportions after splitting
from
collections
import
Counter
(
"Original class distribution:"
,
Counter
(
y
)
)
(
"Training set class distribution:"
,
Counter
(
y_train
)
)
(
"Test set class distribution:"
,
Counter
(
y_test
)
)
Code Analysis:
stratify=y: this is the key parameter. It tells the function to perform stratified sampling according to the label'syclass distribution.
3. Time series data splitting
For time series data (such as stock prices and daily temperatures), there are temporal dependencies between data points. We cannot shuffle randomly, because future data cannot be used to predict the past.
The usual approach is to split by time order:use the first 80% of the time data as the training set and the last 20% as the test set。
Example
Example: sequential splitting of time series data
split_index
=
int
(
len
(
X
)
0.8
)
Compute the index at the 80% position
X_train
,
X_test
=
X
[
:split_index
]
,
X
[
split_index:
]
y_train
,
y_test
=
y
[
:split_index
]
,
y
[
split_index:
]
(
f
"Training set time range: first {split_index} samples"
)
(
f
"Test set time range: last {len(X) - split_index} samples"
)
How to choose the split ratio?
This is a common question, but there is no fixed answer. Common ratios include:
| Ratio (training set:test set) | Applicable scenarios | Advantages | Disadvantages |
|---|---|---|---|
| 70:30 | A classic choice for small to medium datasets (thousands to tens of thousands of samples) | Balances the amount of training data and evaluation reliability | For very small datasets, a 30% test set may have too few samples, making evaluation unstable |
| 80:20 | The more popular default choice today, especially for deep learning | Provides more data for the model to learn from | The test set is relatively small, so the evaluation variance may be slightly larger |
| 90:10 or 95:5 | when data is very limited | maximizes the use of limited data for training | the test set is too small, so evaluation results may be unreliable and have low confidence |
Core principles:
- Ensure the training set is large enough: the model needs enough data to learn effective patterns.
- Ensure the test set is large enough: the test set needs to provide a statistically reliable performance evaluation. Usually, the test set should have at least a few hundred samples for the evaluation results to be relatively stable.
- The larger the amount of data, the proportion allocated to the test set can be relativelysmaller, because even a small proportion may represent a large number of samples.
Advanced concepts: validation set and cross-validation
In real projects, we not only need to evaluate the final model, but also need to adjust the model'sHyperparameters(such as learning rate, tree depth, etc.) during training. If we directly use the test set to tune parameters, then the test set becomes "contaminated" again, losing its fairness as the "final examiner".
For this reason, we introducevalidation set。
the three-dataset split: training set, validation set, test set
- Training Set: used for learning the model parameters.
- validation set: used for tuning hyperparameters, selecting models, or early stopping during training. It is equivalent to a "mock exam".
- Test Set: used for the final, one-time performance evaluation after the model and hyperparameters are determined. It is the "final exam".
Example
Example: first split into train+validation set and test set, then split the validation set out of the train+validation set
X_temp
,
X_test
,
y_temp
,
y_test
=
train_test_split
(
X
,
y
,
test_size
=
0.15
,
random_state
=
42
)
First split off 15% as the final test set
X_train
,
X_val
,
y_train
,
y_val
=
train_test_split
(
X_temp
,
y_temp
,
test_size
=
0.176
,
random_state
=
42
)
Split about 15% from the remaining 85% as the validation set
Calculate the ratio: 0.85 * 0.176 ≈ 0.15, final ratio is about 70:15:15
(
f
"Training set: {len(X_train)}, validation set: {len(X_val)}, test set: {len(X_test)}"
)
K-fold cross validation
When the amount of data is not large, splitting off a separate validation set further reduces the training data.K-fold cross validationis a more powerful solution.
Its workflow is as follows, which can effectively use limited data:
Example
flowchart TD
A[Original dataset] --> B[Randomly shuffle and evenly split into K parts]
B --> C{Perform K rounds of loops}
C --> D[Round i: use the i-th part as the validation set]
D --> E[Merge the remaining K-1 parts as the training set]
E --> F[Train the model on this round's training set]
F --> G[Evaluate the score Si on this round's validation set]
G --> C
C -- After K rounds --> H[Compute the average of the K scores as the final evaluation]
Example
Example: evaluating a model with 5-fold cross-validation
from
sklearn.
model_selection
import
cross_val_score
from
sklearn.
linear_model
import
LogisticRegression
model
=
LogisticRegression
(
)
scores
=
cross_val_score
(
model
,
X
,
y
,
cv
=
5
)
cv=5 means 5-fold cross-validation
(
f
"Scores of each fold: {scores}"
)
(
f
"Average score: {scores.mean():.4f} (+/- {scores.std()*2:.4f})"
)
Output the average score and standard deviation
Advantages of cross-validation:
- Fully utilizes all data for training and validation.
- Evaluation results are more stable and reliable (because it is the average of multiple evaluations).
- It is the gold standard for model selection and parameter tuning on small to medium datasets.
Practice exercise: experiencing data splitting hands-on
Now, let's practice with a simple dataset.
Example
1. Import the necessary libraries
import
numpy
as
np
from
sklearn.
datasets
import
load_iris
from
sklearn.
model_selection
import
train_test_split
2. Load the Iris dataset
iris
=
load_iris
(
)
X
,
y
=
iris.
data
,
iris.
target
(
f
"Dataset shape: features {X.shape}, labels {y.shape}"
)
3. Simple random split (80% training, 20% testing)
X_train
,
X_test
,
y_train
,
y_test
=
train_test_split
(
X
,
y
,
test_size
=
0.2
,
random_state
=
42
)
(
f
"Random split -> training set: {X_train.shape}, test set: {X_test.shape}"
)
4. Stratified random split
X_train_s
,
X_test_s
,
y_train_s
,
y_test_s
=
train_test_split
(
X
,
y
,
test_size
=
0.2
,
stratify
=
y
,
random_state
=
42
)
(
f
"Stratified split -> training set: {X_train_s.shape}, test set: {X_test_s.shape}"
)
5. Check the effect of stratification
(
"\nOriginal class distribution:"
,
np.
bincount
(
y
)
)
(
"Test set distribution after random split:"
,
np.
bincount
(
y_test
)
)
may be imbalanced
(
"Test set distribution after stratified split:"
,
np.
bincount
(
y_test_s
)
)
should be proportional to the original distribution
Your task:
- Run the code above and observe the output.
- Try changing
test_sizeto 0.3 and observe the change in the sizes of the training and test sets. - Try changing
random_stateto another number (such as 7), run again, and observe whether the split result changes. - (Challenge) Do not set
random_statethe parameter, run the code multiple times, and observe whether the split result is the same each time.
Summary and Key Takeaways
- Core purpose: splitting training and test sets is forevaluating the model's generalization ability, preventing overfitting, and ensuring the model can handle new data.
- Golden rule:The test set must be kept completely confidential throughout the entire training process, used only for final evaluation.
- Splitting methods:
- Random split: the most general-purpose.
- Stratified split: suitable for imbalanced data in classification problems.
- Sequential split: suitable for time series data.
- Split ratio: there is no absolute standard; a balance must be struck between "sufficient training" and "reliable evaluation". 80:20 or 70:30 are common starting points.
- Advanced tools:
- validation set: used for model parameter tuning, protecting the purity of the test set.
- K-fold cross validation: a powerful tool for evaluation and parameter tuning on small to medium datasets, with more robust results.