Unit 1.3 · about 4 h
130 / 324Split design, nested selection and test isolation
The split is the claim about the future. A convenient shuffle that mixes weeks or years with the test set measures memorization, not deployment.
- explain
- implement
You can now
- Explain random, stratified, grouped, temporal, and nested splits and the dependence structure each one protects.
- Derive a split and evaluation policy from the data-generating and deployment process rather than from dataset convenience.
- Build a deterministic grouped and temporal split with no entity or future overlap and evaluate a model on it exactly once.
Covers
- Random, stratified, grouped and temporal splits
- Nested selection and final test isolation
Study, in this order
3 steps
- Test-set construction: random, hashed, and stratified splitsHands-On Machine Learning with Scikit-Learn and PyTorch - Chapters 1 and 2
Book Chapter 2: Create a Test Set (printed pp. 57-62). Notebook 02: Create a Test Set:
shuffle_and_split_datawith seed 42,crc32id-hash split with thelongitude/latitudestable-id pattern,train_test_splitwithrandom_state42, the 10.7 percent bad-sample binomial calculation with its simulation check,income_catbinning withpd.cut,StratifiedShuffleSplit, the single stratifiedtrain_test_splitcall, and the Overall/Stratified/Random proportion tableDepth · Use the housing income stratification as the method demo. Your graded split is the chronological Bike rebuild, not housing.
- Selection inside validation, test set touched onceHands-On Machine Learning with Scikit-Learn and PyTorch - Chapters 1 and 2
Book Chapter 2: Fine-Tune Your Model through Evaluate Your System on the Test Set (printed pp. 94-100). Notebook 02: Grid Search and Randomized Search through Evaluate Your System on the Test Set: cross-validated search, best-model error analysis, final test RMSE with the scipy bootstrap 95 percent confidence interval; plus the Chapter 1 Exercise Solutions 16 to 19 on test, validation, and train-dev roles and why tuning on the test set overfits it
Depth · Read the selection-then-final-test order. Do not run the full search here.
- Group-aware, time-aware, and single train/test splitsscikit-learn - Cross-validation splitters
3.1.2.4 Cross-validation iterators for grouped data with 3.1.2.4.1 Group K-fold (
groups[1, 1, 1, 2, 2, 2, 3, 3, 3, 3]giving test folds[6, 7, 8, 9],[3, 4, 5],[0, 1, 2]); 3.1.2.5 Using cross-validation iterators to split train and test (GroupShuffleSplitwithrandom_state7); 3.1.2.6 Cross validation of time series data with 3.1.2.6.1 Time Series Split (n_splits3 on 6 samples); 3.1.3 A note on shuffling
Focus on
- Choose the splitter from the dependence structure. Stratify when a rare subgroup must survive (
income_cat); group when rows share an entity (GroupKFoldholds each ofgroups1, 2, 3 out in turn); go temporal when deployment runs forward in time (TimeSeriesSplittrains[0, 1, 2]tests[3], then expands). - Stratification needs discrete labels, so regression targets get binned first:
pd.cutonmedian_incomeinto 5 cats, stratify, then drop the bin column before training. The Overall/Stratified/Random proportion table is the oracle. - Selection lives inside validation and the test set is touched once. The HOML order is cross-validated search, error analysis, then one final test RMSE with a bootstrap interval; the checklist rule is never tweak after measuring generalization error.
- A random split of bike hours leaks the future: neighboring hours share weather and demand. The honest deployment proxy is the chronological cut at 2012-01-01, giving 8645 train rows and 8734 test rows.
Reproduce closed-book
GroupKFold folds for 10 samples with groups [1, 1, 1, 2, 2, 2, 3, 3, 3, 3] (test folds [6, 7, 8, 9], [3, 4, 5], [0, 1, 2]) and the TimeSeriesSplit(n_splits=3) folds on 6 samples (train [0, 1, 2] test [3], then [0, 1, 2, 3] test [4], then [0, 1, 2, 3, 4] test [5]). Then state the bike chronological counts: 8645 train rows before 2012-01-01 and 8734 test rows from that date.Traps
- Shuffling time-ordered rows before splitting. Section 3.1.3 warns that shuffling news-like data overfits near-time similarity; bike hours need the chronological cut, not a shuffle.
- Stratifying on the raw regression target.
stratifyneeds classes, so bin first withincome_catand drop the bin column before training, exactly as the notebook cells do. - Reusing the test set for selection and reporting it as generalization. Every peek costs the guarantee; fix split identities from the start and let lineage make that mechanical.
Practice
The section mini-project covers this: the chronological Bike split (2011 train, 2012 test) with assertions that no future timestamp and no prohibited group cross the boundary.
Self-test
-
Housing data holds few high-income districts. Why does the notebook bin
median_incomebefore splitting?train_test_splitstratifyneeds discrete labels, sopd.cutmakes 5 income cats and the rare high-income slice keeps its proportion in train and test, verified by the proportion table. -
What is the 10.7 percent number in Create a Test Set?
The binomial probability that a random 1000-person sample at a 51.6 percent female ratio lands below 49 or above 54 percent female. It motivates stratification and is matched by simulation at about 0.108. -
Bike rows from the same week share weather. Which split answers generalization to next year?
The temporal split: train on 2011, test on 2012. Random KFold would place adjacent hours on both sides;GroupKFoldby week answers generalization to new weeks instead, which is a different question. -
Grid search has picked hyperparameters on validation folds. What may you now do with the test set?
Evaluate once for the generalization estimate, with an interval. Do not select, tune, or compare on it afterward, or the estimate turns optimistic.
Completion criterion
Stop when
You derive both fold plans from memory and your Bike split script asserts zero future-timestamp and zero group overlap across the boundary.
Mark passed, then open 1.4 Only mark this when you can do it without notes.Leads to
- 1.4 Leakage: target, future, entity, duplicate, preprocessing and feedback Name every way the split boundary can still leak after it is drawn.
- 1.6 Training-only imputation, scaling, encoding and learned state Fit every learned preprocessing state inside the split built here.
Comes after
- 1.1 Unit of observation, prediction time and label horizonDerive the split from the time and entity boundaries fixed here.
- 1.2 Targets, losses, metrics, decision rules and problem framingEvaluate the chosen metric under a split that respects the decision process.
- 5.1 Holdout, cross-validation and resampling by the right unitMatch the split design to the same dependence structure.
Resources for this unit
- Hands-On Machine Learning with Scikit-Learn and PyTorch - Chapters 1 and 2 Read Chapters 1 and 2 of the book, then run notebooks 01 and 02 and use ml-project-checklist.md for framing, data inspection, test-set creation, preprocessing pipelines, cross-validation, error analysis and persistence. Rebuild the workflow on UCI Bike Sharing with a chronological split and prohibit casual and registered when predicting cnt.
- scikit-learn - Cross-validation splitters Use the group-aware and time-aware splitter sections plus GroupKFold and TimeSeriesSplit. Choose from the dependence structure and assert that no prohibited group or future timestamp crosses the boundary.
Also in this section
- scikit-learn - Common pitfalls and pipelines Read Common Pitfalls sections on inconsistent preprocessing and leakage, then Pipeline and ColumnTransformer. Seed global scaling, a target-derived feature and a partition duplicate, and make tests reject each defect.
- Rules of Machine Learning - first controls Read Rules 1-5 and 8-9. Turn the existing heuristic into a baseline and test the feature path independently of the learner.
- UCI Bike Sharing Dataset Use hour.csv as the compact integrated dataset. Preserve a raw snapshot and data dictionary, split chronologically, and document why casual and registered are target proxies for cnt.
- Google ML Problem Framing - framing an ML problem Read Identify the output you need through Proxy labels and Define the success metrics, including the video-caching threshold analysis, the proxy-issue table, and both Check Your Understanding boxes.