"""Independent offline lab for ML Ch 15: Train/Test Splitting (random, stratified, time-series, 3-way, K-Fold CV)."""
import json
import platform
from collections import Counter
import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, TimeSeriesSplit, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
def main():
cases = []
iris = load_iris()
X, y = iris.data, iris.target
# 1. Random split ratios (80:20, 70:30, 90:10), train_size equivalence & random_state reproducibility
X_tr_80a, X_te_20a, y_tr_80a, y_te_20a = train_test_split(X, y, test_size=0.2, random_state=42)
X_tr_80b, X_te_20b, y_tr_80b, y_te_20b = train_test_split(X, y, train_size=0.8, random_state=42)
X_tr_70, X_te_30, _, _ = train_test_split(X, y, test_size=0.3, random_state=42)
X_tr_90, X_te_10, _, _ = train_test_split(X, y, test_size=0.1, random_state=42)
_, _, _, y_te_seed7 = train_test_split(X, y, test_size=0.2, random_state=7)
same_seed_equal = bool(np.array_equal(X_tr_80a, X_tr_80b) and np.array_equal(y_te_20a, y_te_20b))
diff_seed_diff = not bool(np.array_equal(y_te_20a, y_te_seed7))
c1_ok = (
len(X_tr_80a) == 120
and len(X_te_20a) == 30
and len(X_tr_70) == 105
and len(X_te_30) == 45
and len(X_tr_90) == 135
and len(X_te_10) == 15
and same_seed_equal
and diff_seed_diff
)
cases.append(
dict(
name="random_split_reproducibility_and_ratios",
inputs=dict(dataset="load_iris", n_samples=150, ratios=["80:20", "70:30", "90:10"]),
prerequisites="使用 scikit-learn 鸢尾花 150 条样本核对常见划分比例与随机种子复现性。",
action="分别按 test_size=0.2/0.3/0.1 与 train_size=0.8 划分,并比较 random_state=42 与 7 的差异。",
expected=dict(
split_80_20=[120, 30],
split_70_30=[105, 45],
split_90_10=[135, 15],
train_size_equiv=True,
diff_seed_changes=True,
),
actual=dict(
split_80_20=[len(X_tr_80a), len(X_te_20a)],
split_70_30=[len(X_tr_70), len(X_te_30)],
split_90_10=[len(X_tr_90), len(X_te_10)],
train_size_equiv=same_seed_equal,
diff_seed_changes=diff_seed_diff,
),
measurements=dict(
iris_unstratified_test_counts=np.bincount(y_te_20a).tolist(),
iris_seed7_test_counts=np.bincount(y_te_seed7).tolist(),
),
passed=c1_ok,
)
)
# 2. Stratified split vs unstratified on Iris and 90:10 imbalanced binary dataset
_, _, _, y_te_iris_s = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
iris_strat_counts = np.bincount(y_te_iris_s).tolist()
X_imb = np.arange(200).reshape(200, 1)
y_imb = np.array([0] * 180 + [1] * 20)
_, _, y_imb_tr, y_imb_te = train_test_split(X_imb, y_imb, test_size=0.2, stratify=y_imb, random_state=42)
tr_cnt = dict(Counter(int(v) for v in y_imb_tr))
te_cnt = dict(Counter(int(v) for v in y_imb_te))
c2_ok = iris_strat_counts == [10, 10, 10] and tr_cnt == {0: 144, 1: 16} and te_cnt == {0: 36, 1: 4}
cases.append(
dict(
name="stratified_vs_random_imbalanced_and_iris",
inputs=dict(iris_classes=[50, 50, 50], imbalanced_classes=[180, 20], test_size=0.2),
prerequisites="分别在均衡 3 类鸢尾花与 90:10 不均衡二分类数据上对比 stratify=y 效果。",
action="验证分层划分严格保持鸢尾花测试集 [10, 10, 10] 与不均衡数据 9:1 比例(144:16 / 36:4)。",
expected=dict(iris_strat_test=[10, 10, 10], imb_train_minor=16, imb_test_minor=4),
actual=dict(
iris_strat_test=iris_strat_counts,
imb_train_minor=tr_cnt[1],
imb_test_minor=te_cnt[1],
),
measurements=dict(
iris_random_test=np.bincount(y_te_20a).tolist(),
imb_train_counts=tr_cnt,
imb_test_counts=te_cnt,
),
passed=c2_ok,
)
)
# 3. Time-series sequential split & TimeSeriesSplit expanding windows
t = np.arange(100)
X_ts = t.reshape(-1, 1)
y_ts = np.sin(t / 10.0)
split_idx = int(len(X_ts) * 0.8)
ts_tr, ts_te = X_ts[:split_idx], X_ts[split_idx:]
no_future_leak = int(ts_tr.max()) < int(ts_te.min())
tscv = TimeSeriesSplit(n_splits=4)
fold_bounds = []
expanding_ok = True
for tr_i, va_i in tscv.split(X_ts):
fold_bounds.append([int(tr_i[-1]), int(va_i[0]), int(va_i[-1])])
if int(tr_i.max()) >= int(va_i.min()):
expanding_ok = False
c3_ok = len(ts_tr) == 80 and len(ts_te) == 20 and no_future_leak and expanding_ok and len(fold_bounds) == 4
cases.append(
dict(
name="time_series_sequential_split",
inputs=dict(total_steps=100, holdout_ratio=0.8, ts_cv_splits=4),
prerequisites="时间序列样本按时间戳递增排列,严禁随机打乱导致未来信息泄漏。",
action="验证前 80% 顺序切分与 4 折 TimeSeriesSplit 均严格满足 max(train_t) < min(test_t)。",
expected=dict(train_len=80, test_len=20, strict_chronological=True, tscv_chronological=True),
actual=dict(
train_len=len(ts_tr),
test_len=len(ts_te),
strict_chronological=no_future_leak,
tscv_chronological=expanding_ok,
),
measurements=dict(
train_time_range=[int(ts_tr.min()), int(ts_tr.max())],
test_time_range=[int(ts_te.min()), int(ts_te.max())],
tscv_train_end_and_val_span=fold_bounds,
),
passed=c3_ok,
)
)
# 4. Three-way Train / Validation / Test split (~70:15:15) with zero index overlap
idx_all = np.arange(1000)
y_1000 = np.tile([0, 1], 500)
idx_temp, idx_test, y_temp, _ = train_test_split(idx_all, y_1000, test_size=0.15, stratify=y_1000, random_state=42)
idx_train, idx_val, _, _ = train_test_split(idx_temp, y_temp, test_size=0.176, stratify=y_temp, random_state=42)
s_tr, s_va, s_te = set(idx_train.tolist()), set(idx_val.tolist()), set(idx_test.tolist())
disjoint = len(s_tr & s_va) == 0 and len(s_tr & s_te) == 0 and len(s_va & s_te) == 0
total_preserved = len(s_tr | s_va | s_te) == 1000
c4_ok = disjoint and total_preserved and len(s_te) == 150 and len(s_va) == 150 and len(s_tr) == 700
cases.append(
dict(
name="three_way_train_val_test_split",
inputs=dict(total=1000, first_test_size=0.15, second_val_size=0.176),
prerequisites="先留出 15% 最终测试集,再从剩余 85% 中切分 0.176(0.85*0.176≈0.1496)作为验证集。",
action="验证三份子集精确为 700/150/150、两两交集为空且并集完整覆盖全部 1000 条样本。",
expected=dict(sizes=[700, 150, 150], pairwise_disjoint=True, union_complete=True),
actual=dict(
sizes=[len(s_tr), len(s_va), len(s_te)],
pairwise_disjoint=disjoint,
union_complete=total_preserved,
),
measurements=dict(
effective_ratios=[round(len(s_tr) / 1000, 3), round(len(s_va) / 1000, 3), round(len(s_te) / 1000, 3)]
),
passed=c4_ok,
)
)
# 5. 5-fold Stratified K-Fold CV with Pipeline(StandardScaler, LogisticRegression) strictly inside train split
X_dev, X_holdout, y_dev, y_holdout = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=500, random_state=42))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(pipe, X_dev, y_dev, cv=cv, scoring="accuracy")
pipe.fit(X_dev, y_dev)
holdout_acc = round(float(pipe.score(X_holdout, y_holdout)), 4)
mean_cv = round(float(scores.mean()), 4)
std2_cv = round(float(scores.std() * 2.0), 4)
c5_ok = len(scores) == 5 and mean_cv >= 0.90 and holdout_acc >= 0.90
cases.append(
dict(
name="kfold_cv_pipeline_and_isolation",
inputs=dict(dev_samples=120, holdout_samples=30, cv_folds=5),
prerequisites="先隔离 20% 独立测试集,再在 80% 开发集内用 Pipeline(StandardScaler+LogisticRegression) 做 5 折交叉验证。",
action="确认每折缩放仅在训练折内拟合,输出 5 折均值/两倍标准差及独立留出测试集准确率。",
expected=dict(folds=5, cv_mean_ge_90=True, holdout_acc_ge_90=True),
actual=dict(
folds=len(scores),
cv_mean_ge_90=(mean_cv >= 0.90),
holdout_acc_ge_90=(holdout_acc >= 0.90),
),
measurements=dict(
fold_scores=[round(float(s), 4) for s in scores],
cv_mean=mean_cv,
cv_two_std=std2_cv,
holdout_test_accuracy=holdout_acc,
),
passed=c5_ok,
)
)
payload = dict(
version=platform.python_version(),
system=platform.system(),
cases=cases,
)
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。
入口文件:projects/ml-training-and-test-set-splitting-lab/explore-training-and-test-set-splitting.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-training-and-test-set-splitting.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a504.zip