Part IV — Expert Production Engineering · Chapter 19 · Lesson 4 of 7 · 6 min read
Lesson 4: Cross-Validation, Regularization, and Hyperparameter Search
Lesson level: Advanced
Purpose: Estimate model performance reliably, control model complexity so it generalizes, and choose settings systematically without overfitting the evaluation itself.
Learning objectives
By the end of this lesson you will be able to:
- explain overfitting and underfitting with the bias-variance trade-off
- run k-fold, stratified, group, and time-series cross-validation
- keep preprocessing inside each fold to avoid leakage
- apply L2 (ridge), L1 (lasso), and elastic-net regularization
- search hyperparameters with grid and random search
- use nested cross-validation or a held-out test set to report unbiased results
4.1 Overfitting and underfitting
A model underfits when it is too simple to capture real structure: training and validation errors are both high. It overfits when it learns noise specific to the training data: training error is low but validation error is much higher. The gap between training and validation performance is the most direct symptom.
The bias-variance trade-off describes the tension. Simple models have high bias (systematic error) and low variance (stable across samples). Flexible models have low bias and high variance (they change a lot with the training sample). Regularization, more data, and simpler features reduce variance; richer features and more flexible models reduce bias. The goal is the lowest validation error, not the lowest training error.
4.2 k-fold cross-validation
Cross-validation reuses the training data for evaluation. In k-fold cross-validation the training set is split into k folds (commonly 5 or 10). The model is trained k times, each time on k − 1 folds and evaluated on the remaining one. The k scores are averaged, and their spread shows how stable the estimate is.
| Variant | Use when |
|---|---|
| Stratified k-fold | Classification, especially with imbalance; keeps class proportions in every fold |
| Group k-fold | Several rows per entity; keeps each customer, patient, or device in one fold |
| Time-series split | Predicting the future; each fold trains on earlier data and validates on later data (Chapter 18, Lesson 4) |
| Repeated k-fold | Small datasets; repeat with different seeds and average for a steadier estimate |
Preprocessing belongs inside the fold. If scaling, imputation, or encoding is fitted once on the whole training set and then cross-validated, every validation fold has influenced the preprocessing. Fit preprocessing on the training folds only, every time. Wrapping preprocessing and model in a pipeline (Lesson 6) makes this automatic.
Illustrative listing.
from pealang.ml import Pipeline, cross_validate, StratifiedKFold
pipe = Pipeline([("prep", preprocessor), ("model", LogisticRegression())])
cv = StratifiedKFold(n_splits=5, shuffle=True, seed=42)
scores = cross_validate(pipe, X_train, y_train, cv=cv,
metrics=["pr_auc", "recall", "log_loss"])
print(scores.mean(), scores.std())
4.3 Regularization
Regularization adds a penalty on coefficient size to the training loss, so the model prefers simpler explanations unless the data strongly supports a complex one. The penalty strength is a hyperparameter — a setting chosen before fitting rather than learned from data.
| Method | Penalty | Effect |
|---|---|---|
| L2 (ridge) | Sum of squared coefficients | Shrinks all coefficients smoothly; stabilizes correlated features |
| L1 (lasso) | Sum of absolute coefficients | Drives some coefficients exactly to zero; performs feature selection |
| Elastic net | Mix of L1 and L2 | Selection with stability when features are correlated |
Implementations differ in how they express strength. Some use a penalty weight (often called α or λ) where larger means stronger regularization; others use its inverse (often called C) where larger means weaker regularization. Check the module reference for your installed version and write the direction into your experiment notes; confusing the two inverts every conclusion.
Regularization penalizes coefficient size, so it is only fair when features are on comparable scales. Standardize first (Lesson 1). The intercept is normally not penalized.
4.4 Hyperparameter search
Hyperparameters include penalty strength and type, class weights, feature options, and — for other model families — depth, number of trees, or learning rate. Choose them by cross-validated performance:
- Grid search evaluates every combination of a small set of values. Simple and exhaustive, but the cost grows multiplicatively with each added setting.
- Random search samples combinations from ranges. For the same budget it usually explores important settings better than a grid, because it tries more distinct values of each.
- Log scales suit strength-like settings: try 0.001, 0.01, 0.1, 1, 10, 100 rather than 1, 2, 3, 4.
Illustrative listing.
from pealang.ml import GridSearch
grid = {"model.penalty": ["l2", "l1"],
"model.strength": [0.001, 0.01, 0.1, 1.0, 10.0]}
search = GridSearch(pipe, grid, cv=cv, metric="pr_auc", seed=42)
search.fit(X_train, y_train)
print(search.best_params, round(search.best_score, 4))
print(search.results.sort("mean_score", descending=True).head(5))
Inspect the whole results table, not only the winner. If the best value sits at the edge of the range, extend the range. If many settings score within the fold-to-fold noise of the best, prefer the simplest or most regularized one — the same simplicity rule as Chapter 18, Lesson 5.
4.5 Do not let the search overfit
Hyperparameter search is itself a form of fitting. The best cross-validation score is optimistically biased, because it was selected as the maximum of many noisy estimates. Two remedies:
- Held-out test set: run the search with cross-validation on training data, freeze the winner, refit on all training data, and evaluate once on the test set. This is the default for most projects.
- Nested cross-validation: an outer loop splits the data for evaluation; an inner loop runs the search on each outer training portion. It gives an unbiased estimate of the whole procedure and suits small datasets where a separate test set is too costly.
Common mistakes
- Preprocessing outside the folds: every fitted step must run inside each fold.
- Ignoring groups or time in folds: use group or time-series splits where they apply.
- Regularizing unscaled features: standardize first.
- Confusing strength and inverse strength: check and record the parameter direction.
- Best value at the edge of the grid: extend the range.
- Reporting the best CV score as final performance: evaluate once on a held-out test set or use nested CV.
- Huge grids: prefer random search with a fixed budget and seed.
Guided practice
- Plot training and validation scores against regularization strength and mark the under- and overfitting regions.
- Compare the cross-validated score with preprocessing inside versus outside the folds.
- Fit lasso at increasing strength and record which coefficients reach zero first.
Hands-on lab: A disciplined model search
- Build a pipeline of the Lesson 1 preprocessing and logistic regression.
- Run stratified, customer-grouped 5-fold cross-validation with a fixed seed.
- Search penalty type and strength on a log scale with PR AUC as the primary metric; record recall and log loss as secondary metrics.
- Choose the simplest setting within one standard deviation of the best mean score.
- Refit on all training data and evaluate once on the test set; compare with the cross-validated estimate and explain any gap.
Review questions
- How do you recognize overfitting from training and validation scores?
- How does k-fold cross-validation work?
- Why must preprocessing be fitted inside each fold?
- What is the practical difference between L1 and L2 regularization?
- Why is random search often more efficient than grid search?
- Why is the best cross-validation score optimistic?
- When is nested cross-validation worth its cost?
Applied challenge
A team has only 600 labelled examples of equipment failures from 40 machines. Design an evaluation procedure that avoids leakage between machines, compares three model configurations fairly, and reports an unbiased estimate without a separate test set. Implement it and report the mean and spread of the outer-loop scores.
Lesson summary
Cross-validation gives a reliable estimate by evaluating on several folds, provided folds respect classes, groups, and time, and preprocessing is fitted inside each fold. Regularization controls complexity and must be applied to scaled features with a clearly recorded strength direction. Search hyperparameters systematically, prefer simple settings within noise of the best, and report final performance on data the search never saw.
Transition to Lesson 5
So far the targets have been binary and the threshold has been 0.5. Lesson 5 extends classification to many classes, checks whether probabilities can be trusted, and chooses thresholds from business costs.
Lesson status: Ready for review.