Launch the interactive walkthrough to discover each component, including the 3D Q-Sphere Lab & Python in Colab.
Learn why evaluating models on unseen data is essential, and master train-test splits, validation sets, and K-fold cross-validation.
| Symbol / Term | Meaning | Beginner Interpretation |
|---|---|---|
| Cross-validation error | Estimated real-world error | |
| Number of folds | Typically 5 or 10 | |
| Error on fold k | Performance metric on fold k |
5-fold CV with fold accuracies: 85%, 88%, 86%, 84%, 87%.
Result: Expected generalization accuracy: 86.0%
Split dataset into 80% train and 20% test using stratified sampling.
Calculate scalers and encoders using training data ONLY to prevent leakage.
Tune hyperparameters using K-fold splits within the training partition.
Evaluate final winning model once on the untouched test partition.
Problem: Evaluating diagnostic models on small patient cohorts.
Solution: Stratified 5-fold cross-validation ensures balanced representation of rare disease subtypes across folds.
Problem: Standard random splits leak future financial prices into past training data.
Solution: Time-Series Split enforces strictly chronological forward validation without lookahead bias.
Interactive activity component
Use scikit-learn to perform proper stratified splits and 5-fold cross-validation.
For Google Colab or Jupyter notebooks, run this shell command to install the required dependencies:
!pip install scikit-learn1 from sklearn.datasets import load_iris 2 from sklearn.model_selection import train_test_split, cross_val_score 3 from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris → Load benchmark dataset
from sklearn.model_selection import train_test_split, cross_val_score → Split & CV utilities
from sklearn.ensemble import RandomForestClassifier → Random forest model
1 X, y = load_iris(return_X_y=True) 2 3 # 1. Strict Train / Test Split (80% Train, 20% Test) 4 X_train, X_test, y_train, y_test = train_test_split( 5 X, y, test_size=0.20, random_state=42, stratify=y 6 ) 7 8 clf = RandomForestClassifier(n_estimators=50, random_state=42) 9 10 # 2. 5-Fold Cross-Validation on Training Data: 11 cv_scores = cross_val_score(clf, X_train, y_train, cv=5) 12 print("5-Fold CV Accuracy Scores:", cv_scores.round(3)) 13 print(f"Mean CV Accuracy: {cv_scores.mean():.3f} +/- {cv_scores.std():.3f}") 14 15 # 3. Final Test Evaluation (Once only!): 16 clf.fit(X_train, y_train) 17 test_acc = clf.score(X_test, y_test) 18 print(f"Final Unseen Test Accuracy: {test_acc:.3f}")
X, y = load_iris(return_X_y=True)
Load 150 iris flower samples
# 1. Strict Train / Test Split (80% Train, 20% Test)
Holdout split
X_train, X_test, y_train, y_test = train_test_split(
Partition data
X, y, test_size=0.20, random_state=42, stratify=y
Maintain class ratios
)
Finish split
clf = RandomForestClassifier(n_estimators=50, random_state=42)
Create model
# 2. 5-Fold Cross-Validation on Training Data:
Cross-validation
cv_scores = cross_val_score(clf, X_train, y_train, cv=5)
5 validation rounds
print("5-Fold CV Accuracy Scores:", cv_scores.round(3))
Print fold scores
print(f"Mean CV Accuracy: {cv_scores.mean():.3f} +/- {cv_scores.std():.3f}")
Mean & variance
# 3. Final Test Evaluation (Once only!):
Final verification
clf.fit(X_train, y_train)
Fit on full train set
test_acc = clf.score(X_test, y_test)
Score on held-out test
print(f"Final Unseen Test Accuracy: {test_acc:.3f}")
Print final score
Click "Copy for Colab", open Google Colab, paste into a single cell, and run.
1 # ========================================================= 2 # Robust Train-Test Splitting & Cross-Validation 3 # Prepared for Google Colab (Run with Shift + Enter) 4 # ========================================================= 5 6 # Step 1: Install required packages 7 !pip install scikit-learn 8 9 # Step 2: Import libraries 10 from sklearn.datasets import load_iris 11 from sklearn.model_selection import train_test_split, cross_val_score 12 from sklearn.ensemble import RandomForestClassifier 13 14 # Step 3: Run Demonstration 15 X, y = load_iris(return_X_y=True) 16 17 # 1. Strict Train / Test Split (80% Train, 20% Test) 18 X_train, X_test, y_train, y_test = train_test_split( 19 X, y, test_size=0.20, random_state=42, stratify=y 20 ) 21 22 clf = RandomForestClassifier(n_estimators=50, random_state=42) 23 24 # 2. 5-Fold Cross-Validation on Training Data: 25 cv_scores = cross_val_score(clf, X_train, y_train, cv=5) 26 print("5-Fold CV Accuracy Scores:", cv_scores.round(3)) 27 print(f"Mean CV Accuracy: {cv_scores.mean():.3f} +/- {cv_scores.std():.3f}") 28 29 # 3. Final Test Evaluation (Once only!): 30 clf.fit(X_train, y_train) 31 test_acc = clf.score(X_test, y_test) 32 print(f"Final Unseen Test Accuracy: {test_acc:.3f}")
Data is separated into 120 training samples and 30 untouched test samples.
Model is trained and evaluated across 5 internal folds, averaging 95.8% accuracy.
Evaluated once on test data, confirming 96.7% generalization without memorization.
150 Iris flower samples with 4 features each
5-Fold CV Accuracy Scores: [0.958 0.958 0.917 1. 0.958] Mean CV Accuracy: 0.958 +/- 0.026 Final Unseen Test Accuracy: 0.967
Consistent scores between cross-validation (95.8%) and unseen test accuracy (96.7%) confirm genuine generalization.
NumPy arrays, pandas DataFrames, train-test splits, and scikit-learn models.
Test your understanding with these questions. Remember, this is for learning, not examination!