Give Each Observation a Role
Suppose you compare two feature choices and keep the one with the better score.
The rows behind that score have helped make a decision, even if their labels
never entered the model's fit call. You need other observations to evaluate
the procedure after making those decisions.
For the fictional parcel contract, assume rows are independent: observing one parcel does not reveal a shared hidden unit effect or future record of another. They follow the same generation law. This is the IID setting: independent and identically distributed observations. A random split is useful for new parcels under that same law. Shuffling does not establish this assumption in a real dataset; repeated people, machines, image sources or time dependence need the next lessons' boundaries.
| Role and row count | What they may influence |
|---|---|
| Fitting: 360 | Fitted parameters and internal fold comparisons during development |
| Development decisions: 120 | Later choices such as a candidate comparison under a stated protocol |
| Final: 120 | Evaluation after the procedure and decisions are frozen |
The first two roles form a 480-row development pool. “Validation” means held-out data used during development; it can refer to a dedicated decision set or to the held-out part of a fold. Always name its precise role. These three roles are this exercise's teaching protocol, not a requirement that every experiment use both a dedicated decision set and folds. Later probability and threshold exercises require more explicit development roles.

Final evaluation stays outside the development decisions. Follow the arrows from 600 rows to the two outer roles, then follow only the development branch to fitting and decision data. The fold arrows stay inside the 360 fitting rows; neither the 120 decision rows nor the 120 final rows enter these folds. No arrow represents a model fit in this lesson: we inspect membership first.
Stratification Preserves Approximate Class Shares
train_test_split selects disjoint parts from matching arrays. Here you split
an array of original row positions, then use those positions to retrieve rows.
test_size=120 requests 120 rows in the second returned part. random_state
fixes the shuffle for a reproducible split in the stated environment.
With stratify=y, the splitter allocates approximately each class's existing
share to each part. It does not make the classes equally frequent or create
new examples. The seed 17 parcel data has 350 class-0 and 250 class-1 rows;
360 fitting rows therefore have 210 and 150. Rounding can prevent exact shares
in other sample sizes. Every required role needs enough class support: a single
minority observation cannot be placed in both disjoint stratified parts.
The second split operates on the 480 development positions. Its matching
labels must be y[development], not all 600 labels. The seed numbers 41/42 are
recorded choices, not scientifically better seeds. Do not try many splits and
keep whichever produces a convenient score.
We deliberately read labels to stratify and report class support when designing the partition. That limited design use is disclosed; it is not a final model evaluation. We produce no predictions or scores. Once roles are set, final observations must not influence fitted transformations, candidate choices, thresholds or stopping rules. A CSV alone cannot enforce that behaviour.
A Fold Is a Pair of Index Sets
Three-fold validation divides the fitting pool into three held-out portions. For each fold, train on two portions (240 rows) and hold out the third (120 rows). Across the three folds, every fitting row is held out once and used for training twice. Train and held-out rows are disjoint within a fold; training sets across folds overlap by design. A fold's validation role changes with the iteration; it is not three independent final test sets.
StratifiedKFold(n_splits=3, shuffle=True, random_state=43) fixes that allocation.
Calling .split(fitting, y[fitting]) gives an iterator: each loop receives
(train_local, held_local), integer positions within the supplied fitting array.
Map them back with fitting[train_local] and fitting[held_local]. For example,
if a fitting array were [9, 2, 7, 5], a local index [0, 2] would identify
original rows [9, 7], not original rows [0, 2].
The splitter uses the first argument's length here; row positions are metadata,
not model features. The next preprocessing lessons will fit fresh learned
state on each fold's training rows and transform its held-out rows separately.
Do not fit one model on all 360 first and call its three subset scores
cross-validation. We are not fitting any model yet, so missing measurements
and the service strings do not need to be imputed or encoded here.
Practice: Write and Inspect a Membership Manifest
Start with the CPU environment from setup and the parcel contract from the previous lesson. No download or new install is needed. The bounded task creates 600 rows and three folds; it performs zero model fits. From Bash:
practice_root="$HOME/feature-evaluation-practice"
cd "$practice_root"
source .venv/bin/activate
mkdir -p choose-evaluation-splits
cd choose-evaluation-splits
pwd
python -c 'import sys; print(sys.executable)'
Check the owned folder and that the interpreter is under the shared .venv.
On a return visit, preserve wanted outputs before rerunning. Save the complete
unchanged D01 generator below as inputs.py. Its formula was explained in
the arrays lesson; seed 17 repeats that teaching population, not the later
challenge's fresh sample.
"""Original fictional parcel recipe; no external data or final-challenge sample."""
import numpy as np
import pandas as pd
def make_parcels(n=600, seed=17):
"""Independent fictional parcels, with both regression and binary targets."""
rng = np.random.default_rng(seed)
distance = rng.uniform(10, 120, n)
weight = rng.lognormal(mean=1.3, sigma=0.4, size=n)
hour = rng.integers(0, 24, n)
load = rng.uniform(0, 1, n)
service = rng.choice(["economy", "priority"], size=n, p=[0.65, 0.35])
duration = (
0.07 * distance + 0.2 * weight + 2 * load
+ 1.5 * (service == "economy")
+ 0.8 * np.sin(2 * np.pi * hour / 24)
+ rng.normal(0, 1.2, n)
)
duration = np.maximum(duration, 0.1)
late = (duration > 8).astype(int)
data = pd.DataFrame({
"parcel_id": [f"parcel-{i:04d}" for i in range(n)],
"distance_km": distance,
"weight_kg": weight,
"dispatch_hour": hour,
"load_at_dispatch": load,
"service": service,
"duration_hours": duration,
"late": late,
"final_status": np.where(late, "arrived-late", "arrived-within-window"),
})
# Introduce missing measurements after generating targets. The complete
# values describe the fictional process; they are not available to a model.
for column in ["distance_km", "weight_kg"]:
data.loc[rng.random(n) < 0.06, column] = np.nan
return data
Save the complete script below as run.py. A manifest is a table that
records membership explicitly so you can trace a row instead of guessing its
role from the order in an array.
"""Inspect independent-parcel roles and fixed folds; fit no model."""
import json
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold, train_test_split
from inputs import make_parcels
def check_partition(parts, population):
"""Reject duplicate, overlapping, missing or foreign row positions."""
sets = [set(part.tolist()) for part in parts]
assert all(len(part) == len(s) for part, s in zip(parts, sets)), "duplicate row"
for i, left in enumerate(sets):
for right in sets[i + 1:]:
assert left.isdisjoint(right), "overlapping roles"
assert set.union(*sets) == set(population.tolist()), "wrong population"
def main():
data = make_parcels(n=600, seed=17)
positions = np.arange(len(data))
y = data["late"].to_numpy()
assert data["parcel_id"].is_unique
development, final = train_test_split(
positions, test_size=120, stratify=y, random_state=41,
)
fitting, decision = train_test_split(
development, test_size=120, stratify=y[development], random_state=42,
)
parts = [fitting, decision, final]
names = ["fitting", "development_decisions", "final"]
check_partition(parts, positions)
print("Data seed 17; role seeds 41/42; fold seed 43")
for name, rows in zip(names, parts):
counts = np.bincount(y[rows], minlength=2).tolist()
assert min(counts) >= 3, "too little support for this exercise"
print(f"{name}: rows={len(rows)}; class[0,1]={counts}")
# split() returns positions WITHIN fitting, not original-table positions.
splitter = StratifiedKFold(n_splits=3, shuffle=True, random_state=43)
held_count = np.zeros(len(data), dtype=int)
fold_records = []
for fold, (train_local, held_local) in enumerate(splitter.split(fitting, y[fitting]), start=1):
train_rows, held_rows = fitting[train_local], fitting[held_local]
check_partition([train_rows, held_rows], fitting)
assert set(held_rows).isdisjoint(set(decision) | set(final))
assert min(np.bincount(y[train_rows], minlength=2)) > 0
assert min(np.bincount(y[held_rows], minlength=2)) > 0
held_count[held_rows] += 1
print(f"fold {fold}: train={len(train_rows)}; held_out={len(held_rows)}")
for partition, rows in [("train", train_rows), ("held_out", held_rows)]:
fold_records.extend({
"fold": fold, "partition": partition,
"parcel_id": data.iloc[int(row)]["parcel_id"],
} for row in rows)
assert np.all(held_count[fitting] == 1), "each fitting row must be held out once"
assert np.all(held_count[decision] == 0) and np.all(held_count[final] == 0)
role_records = [{"parcel_id": data.iloc[int(row)]["parcel_id"], "role": name}
for name, rows in zip(names, parts) for row in rows]
output = Path(__file__).resolve().parent
pd.DataFrame(role_records).sort_values("parcel_id").to_csv(output/"roles.csv", index=False)
pd.DataFrame(fold_records).sort_values(["fold", "partition", "parcel_id"]).to_csv(
output/"folds.csv", index=False,
)
protocol = {
"dataset": "D01", "data_seed": 17, "n": 600,
"role_split_seeds": [41, 42], "fold_seed": 43, "n_splits": 3,
"assumption": "independent fictional parcels under one generation law",
"design_label_use": "stratification and class-support counts only; no model scoring",
}
(output/"protocol.json").write_text(json.dumps(protocol, indent=2) + "\n")
print("PASS: partition, fold coverage and class-support assertions")
print("Saved roles.csv, folds.csv and protocol.json beside run.py")
if __name__ == "__main__":
main()
Run it and inspect the first rows of its outputs:
python run.py
head -n 5 roles.csv
head -n 5 folds.csv
cat protocol.json
Illustrative console output from the checked environment:
Data seed 17; role seeds 41/42; fold seed 43
fitting: rows=360; class[0,1]=[210, 150]
development_decisions: rows=120; class[0,1]=[70, 50]
final: rows=120; class[0,1]=[70, 50]
fold 1: train=240; held_out=120
fold 2: train=240; held_out=120
fold 3: train=240; held_out=120
PASS: partition, fold coverage and class-support assertions
Saved roles.csv, folds.csv and protocol.json beside run.py
np.arange creates the original positions 0–599. check_partition converts
each part to a Python set, checks for duplicates within it, compares every
pair for overlap, then checks the union equals the declared population. A
union alone is insufficient: overlapping roles can still cover all rows.
assert stops with an AssertionError when a required condition is false;
run normally as shown, without Python's -O option which disables assertions.
These checks inspect our known fixture; they are not a general production
validation system.
The script's minimum of three observations per class in each role is a mechanical condition for this exercise, not evidence of statistically adequate evaluation support. Three-fold training uses only the fitting role.
held_count starts as 600 zeros. Advanced indexing adds one at each held-out
position per fold; the final assertions require one for every fitting row and
zero for the other roles. The script writes roles.csv with one row per parcel
and folds.csv with 1,080 records: 360 fitting rows appear in each of three
folds. protocol.json stores the data/split seeds and assumption as structured
text. Outputs go beside run.py, so an accidental working-directory change
does not scatter them. Importing inputs.py may also create __pycache__.
Success: all assertions pass; the role table has 600 unique IDs; each fitting ID has one held-out and two training memberships in the fold table; decision/final IDs have none. Choose one ID from each role and explain its permitted influence. Rerunning the unchanged script should reproduce the manifests in the pinned environment; seeds are not a cross-version guarantee.
Independent Task: Find Overlap and Insufficient Support
Before opening the answer, save and run this as broken_roles.py:
"""Intentional overlap: attempt a repair before reading the answer."""
fitting = {0, 1, 2}
decision = {2, 3}
final = {4, 5}
population = set(range(6))
assert fitting.isdisjoint(decision), "overlapping roles"
assert fitting.isdisjoint(final) and decision.isdisjoint(final)
assert fitting | decision | final == population
print("PASS: toy role partition")
Predict the first failing assertion. Repair the role sets so positions 0–5 appear exactly once; keep position 2 in fitting. Explain why checking only the union would have missed this mistake.
Next save and run this complete counterexample as rare_class.py:
"""Intentional support failure: one minority row cannot enter both parts."""
import numpy as np
from sklearn.model_selection import train_test_split
labels = np.array([0, 0, 0, 0, 0, 1])
train_test_split(np.arange(6), test_size=2, stratify=labels, random_state=41)
Explain why this fails even though there are six rows. Would removing
stratify establish enough minority support for both parts? Would copying the
single minority row into both parts create an independent evaluation?
A separate pool has six class-0 and two class-1 observations. If you require both classes in every held-out fold, can it support three stratified folds? Explain your response even if the library only warns and continues.
Also answer: two observations have different row IDs but are measurements of
the same machine. Does passing check_partition justify this random split for
an unseen-machine prediction? What must change?
Answer and Reasoning
Hint 1: A member can occur in the union once while being present in two sets. Hint 2: Count distinct observations of each class, not just total rows.
The first assertion fails because position 2 is in fitting and decision. Save
this complete reference as fix_roles.py and run python fix_roles.py:
"""Reference repair: position 2 belongs only to fitting."""
fitting = {0, 1, 2}
decision = {3}
final = {4, 5}
population = set(range(6))
assert fitting.isdisjoint(decision), "overlapping roles"
assert fitting.isdisjoint(final) and decision.isdisjoint(final)
assert fitting | decision | final == population
print("PASS: toy role partition")
It prints PASS: toy role partition. Removing 2 from decision preserves all
six positions and makes the roles disjoint. Other repairs can be valid if
they preserve the stated conditions. The union check on the original broken
sets already passes, so it cannot detect overlap on its own.
The rare-class example raises ValueError: the least-populated class has one
member. A stratified split requires at least two per class, and its requested
part sizes must also accommodate all classes. For stratified folds, enough
minority observations are needed for every held-out fold; this course checks
support explicitly rather than relying on a warning. Merely setting fewer
folds cannot put one independent observation into two independent roles.
Unstratified splitting can run while leaving a part with no minority examples;
duplicating that row across roles leaks the same observation. Obtain more
independent examples, or revise the evaluation question and report what the
data can support. No seed fixes missing evidence.
Two minority observations cannot fill three disjoint held-out folds with that
class. StratifiedKFold can warn and return a class-empty fold in this situation;
do not confuse successful iteration with the required support. Two folds can
satisfy this mechanical class-presence condition, or you can collect additional
independent observations. Neither response alone establishes a precise estimate.
Different row IDs establish row disjointness, not machine independence. Keep every measurement of the same machine in one outer role when estimating unseen-machine performance. That is the next lesson's group boundary. A group holdout still needs its own time/availability reasoning where applicable.
Diagnose, Resume and Reset
| Symptom | Check | Response |
|---|---|---|
ModuleNotFoundError: inputs | Is the complete inputs.py beside run.py? | Save it there; do not install a package named inputs |
| Import failure for numpy/sklearn | Does sys.executable point inside the shared .venv? | Resume setup and activate that environment |
| Inconsistent sample counts | Did the second split use y instead of y[development]? | Match labels to the exact supplied positions |
overlapping roles | Which ID occurs in two roles? | Repair the assignment; preserve the failure as evidence |
Least-populated-class error in rare_class.py | Is there only one class-1 observation? | Expected counterexample; explain the support limit |
| Held-out original IDs look wrong | Were local fold positions mapped through fitting? | Restore the mapping before interpreting membership |
To resume, return to the exercise folder, activate .venv, confirm both starter
files and inspect the last complete outputs. An interrupted run can leave a
partial output file; preserve wanted work and rerun the unchanged script to
regenerate all three. Nothing in this task trains a model or uses final scores.
After completing the independent task, reset only the generated files if wanted:
pwd
ls -l roles.csv folds.csv protocol.json
rm -i -- roles.csv folds.csv protocol.json
Read pwd and the listed filenames before confirming each removal. Keep source
files, your explanation, wanted manifests, earlier exercises and the shared
environment. Rerun python run.py to restore outputs. You are ready to continue
when you can trace local and original indices and explain why repeatable,
stratified, row-disjoint partitions still need a justified independence claim.
Sources
- S14 — scikit-learn cross-validation guide: holdout/fold roles, stratification and group/time limits; checked against 1.9.1.
- S65 — NumPy Generator: seeded teaching data, with the limits of reproducibility.
- S81 — NumPy indexing: mapping integer positions back to original arrays.