Mọi bước preprocessing — impute, scale, encode — đều giả định bạn đã tách dữ liệu thành tập huấn luyện và tập đánh giá. Train/test split là ranh giới bảo vệ metric khỏi overfitting và data leakage. Kungfutech Chương 4 nhắc đến split sớm trong workflow; bài này đi sâu train_test_split và các biến thể quan trọng.
Mục tiêu
- Chia dữ liệu với tỷ lệ train/test phù hợp và
random_statereproducible. - Dùng stratify cho classification imbalanced hoặc multiclass.
- Hiểu khi nào cần validation set riêng và liên hệ với cross-validation.
Lý thuyết
Vì sao cần tách tập?
Mô hình học pattern từ $X_{train}, y_{train}$. Nếu đánh giá trên cùng tập, metric phản ánh khả năng ghi nhớ (overfit) chứ không phải khái quát hóa. Tập test $X_{test}, y_{test}$ giữ kín trong quá trình chọn model và tune hyperparameter — chỉ dùng một lần cuối cùng (hoặc dùng CV trên train).
Quy trình Kungfutech:
- Split train / test
- Preprocessing fit chỉ trên train
- Tune trên train (CV)
- Báo cáo cuối trên test
train_test_split cơ bản
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y,
test_size=0.25, # 25% test, 75% train
random_state=42, # reproducible shuffle
stratify=y, # giữ tỷ lệ class
)
| Tham số | Ý nghĩa |
|---|---|
test_size |
float (0–1) hoặc int (số mẫu test) |
train_size |
bổ sung cho test_size nếu cần |
random_state |
seed shuffle — cùng seed → cùng split |
stratify |
array — chia đều tỷ lệ class/theo nhóm |
shuffle |
True (mặc định) — xáo trộn trước split |
Stratified split
Với $y$ imbalance — Breast Cancer ~63% benign — split ngẫu nhiên có thể cho test 70/30 tình cờ. stratify=y đảm bảo train và test có cùng tỷ lệ class:
$$P(y=c \mid \text{train}) \approx P(y=c \mid \text{test}) \approx P(y=c \mid \text{full})$$
Bắt buộc với classification multiclass nhỏ (Wine 3 class, Iris 3 class).
Train / Validation / Test — ba tầng
| Tập | Mục đích |
|---|---|
| Train | Fit model + preprocessing |
| Validation | Chọn hyperparameter, so sánh model |
| Test | Estimate generalization cuối — không tune |
train_test_split hai lần:
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.3, stratify=y)
X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, stratify=y_temp)
# → 70% train, 15% val, 15% test
Hoặc dùng cross_val_score trên train thay validation riêng — tiết kiệm data khi mẫu ít.
Khi nào không shuffle?
Time series: shuffle phá thứ tự thời gian — split theo thời gian (train = quá khứ, test = tương lai). TimeSeriesSplit cho CV.
Group data: cùng patient / user xuất hiện train và test → leakage. Dùng GroupShuffleSplit.
Iris, Wine, Breast Cancer — shuffle + stratify là đủ.
Data leakage qua split sai thứ tự
Sai thứ tự workflow:
scaler.fit_transform(X) # fit trên ALL data
X_train, X_test = train_test_split(X_scaled, ...)
Đúng:
X_train, X_test, y_train, y_test = train_test_split(X, y, ...)
scaler.fit(X_train)
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test)
Split trước mọi bước học tham số từ dữ liệu.
Tỷ lệ split thực tế
| Quy mô dataset | Gợi ý test_size |
|---|---|
| <500 mẫu | 0.2–0.3 + CV |
| 500–10K | 0.2 |
| >10K | 0.1–0.2 đủ |
Iris 150 mẫu: test 25% ≈ 37 mẫu — nhỏ nhưng OK cho demo; production dùng CV.
Code Python
Stratified split và so sánh metric trên Breast Cancer:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
data = load_breast_cancer()
X, y = data.data, data.target
class_names = data.target_names
# Stratified split
X_train, X_test, y_train, y_test = train_test_split(
X, y,
test_size=0.25,
random_state=42,
stratify=y,
)
# Kiểm tra tỷ lệ class
def class_ratio(y_arr, name):
unique, counts = np.unique(y_arr, return_counts=True)
ratios = counts / len(y_arr)
print(f"{name}: {dict(zip(unique, ratios.round(3)))}")
class_ratio(y, "Full")
class_ratio(y_train, "Train")
class_ratio(y_test, "Test")
# Pipeline — fit CHỈ train
pipe = Pipeline([
("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=1000, random_state=42)),
])
pipe.fit(X_train, y_train)
train_acc = accuracy_score(y_train, pipe.predict(X_train))
test_acc = accuracy_score(y_test, pipe.predict(X_test))
print(f"\nTrain accuracy: {train_acc:.3f}")
print(f"Test accuracy: {test_acc:.3f}")
# CV trên train (không đụng test)
cv_scores = cross_val_score(pipe, X_train, y_train, cv=5, scoring="accuracy")
print(f"CV on train: {cv_scores.mean():.3f} (+/- {cv_scores.std():.3f})")
print("\nTest report:")
print(classification_report(y_test, pipe.predict(X_test), target_names=class_names))
# Reproducibility: cùng random_state → cùng split
X_tr2, X_te2, _, _ = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
assert np.array_equal(X_train, X_tr2)
print("\nReproducible split verified (random_state=42).")
Gap train_acc > test_acc gợi ý overfit nhẹ — bình thường; gap lớn cần regularization.
Lỗi thường gặp
- Tune hyperparameter trên test: Test không còn unbiased — dùng validation hoặc CV trên train.
- Không stratify với class imbalance: Test thiếu class hiếm — metric không ổn định.
- Preprocess trước split: Leakage thống kê từ test vào train — split trước, fit sau.
- Dùng test nhiều lần: "Peeking" test lặp lại khi thử model — lạc quan giả dần; giữ test hold-out thật sự.
Bài tập
- Stratify vs không: Split Wine với/không
stratify=y100 lần (random_statekhác nhau). Vẽ histogram tỷ lệ class 0 trong test — stratify có ổn định hơn không? - Ba tầng: Chia Breast Cancer thành 60/20/20 train/val/test. Tune
Ccủa LogisticRegression trên val, báo cáo accuracy cuối trên test (chỉ một lần). - Đọc docs:
train_test_split—shuffle=Falsedùng khi nào? Liên hệ với time series.
Tóm tắt
Train test split tách dữ liệu trước preprocessing và modeling — bảo vệ metric và tránh leakage. Dùng stratify=y cho classification, random_state cho reproducibility. Tune trên train/CV; test giữ làm đánh giá cuối. Split đúng thứ tự là điều kiện tiên quyết cho mọi bước preprocessing Kungfutech Chương 4.
Tiếp tục tại khóa Machine Learning cơ bản — bài tiếp theo: Feature Scaling — chuẩn hóa và chuẩn tắc hóa.