Common Values for \(K\): \(K=5\) or \(K=10\) (good trade-off between computational cost and bias/variance).
Leave-One-Out Cross-Validation (LOO-CV)
An extreme case of \(K\)-Fold CV where \(K = N\) (\(N\) = total number of samples).
For each iteration:
Train on \(N-1\) samples.
Test on the single \(1\) remaining sample.
Advantages:
Unbiased performance estimation (uses almost all data for training).
Fully deterministic (no randomness in splitting).
Disadvantages:
High computational cost (fits \(N\) separate models).
High variance in evaluation error.
Code: Leave-One-Out CV in Scikit-Learn
from sklearn.model_selection import LeaveOneOut, cross_val_scorefrom sklearn.linear_model import LogisticRegressionfrom sklearn.datasets import load_iris# Load datasetX, y = load_iris(return_X_y=True)# Initialize LeaveOneOut iteratorloo = LeaveOneOut()model = LogisticRegression(max_iter=1000)# Evaluate using LOO (fits 150 times for Iris dataset)scores = cross_val_score(model, X, y, cv=loo, scoring='accuracy')print(f"Number of fits (N): {len(scores)}")print(f"LOO-CV Mean Accuracy: {scores.mean():.4f}")
Code: Implementing Cross-Validation in Scikit-Learn
Model Selection is the process of selecting the optimal machine learning algorithm (or architecture) among a set of candidate models for a given problem.
Examples of candidate models:
Logistic Regression vs. Support Vector Machines vs. Decision Trees vs. Random Forests.
Goal
Identify the model architecture that generalizes best to unseen data.
What Makes a Good Model?
When comparing candidate models, consider:
Strong performance — high accuracy, low mean squared error, etc.
Consistent performance — similar results across cross-validation or different data splits.
Reasonable assumptions — model assumptions are appropriate and not seriously violated.
Interpretability — the model is understandable when interpretation is important.
Key Idea
There is often no single best model.
We want a model that generalizes well while balancing:
#| eval: falsefrom sklearn.model_selection import GridSearchCVfrom sklearn.ensemble import RandomForestClassifier# Define candidate model and search spacerf = RandomForestClassifier(random_state=42)param_grid = {'n_estimators': [25, 50, 100],'max_depth': [3, 5, None],'min_samples_split': [2, 5]}# Set up Grid Search with 5-Fold CVgrid_search = GridSearchCV(estimator=rf, param_grid=param_grid, cv=5, scoring='accuracy', n_jobs=-1)grid_search.fit(X_train_val, y_train_val)print("Best Parameters:", grid_search.best_params_)print(f"Best CV Accuracy: {grid_search.best_score_:.4f}")# Evaluate optimal model on holdout test setbest_model = grid_search.best_estimator_test_accuracy = best_model.score(X_test, y_test)print(f"Final Holdout Test Accuracy: {test_accuracy:.4f}")
Optimization bias
Pizza baking competition example
Imagine that you participate in pizza baking competition.
Training phase: Collecting recipes and practicing at home
Validation phase: Inviting a group of friends for tasting and feedback
Test phase (competition day): Serving the judges
Overfitting on the validation set
Your friends loved your pineapple pizza.
You fine-tune your recipe for the same group of friends, perfecting it for their tastes.
On the competition day, you confidently present your perfected pineapple pizza.
Judges are not impressed: “This doesn’t appeal to a broad audience.”
This is similar to reusing the same validation set again and again to perfect the model for it!
Lesson: Overfitting on the validation set
You tailored your recipe too closely to your friends’ tastes.
They were not representative of the broader audience (the judges).
The pizza, while perfect for your validation group, failed to generalize.
Over many iterations, the validation set no longer gives an unbiased estimate of performance.
That’s why we need a separate test set (like a group of tasters who never influenced your pizza).
Optimization bias
Why do we need separate validation and test datasets?
Mitigating optimization bias
Cross-validation
Ensembles
Regularization and choosing a simpler model
Interpreting Validation Curves
A Validation Curve plots training and validation scores against a single hyperparameter’s values.
Validation curves are useful for detecting overfitting: - Hyperparameters that are overfitted will have high training scores and low validation scores. - Optimal hyperparameters will perform well on the training sets and the validation sets.