PeaBox Lab › PeaLang › Learn › Chapter 19 › Lesson 4

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:

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.

VariantUse when
Stratified k-foldClassification, especially with imbalance; keeps class proportions in every fold
Group k-foldSeveral rows per entity; keeps each customer, patient, or device in one fold
Time-series splitPredicting the future; each fold trains on earlier data and validates on later data (Chapter 18, Lesson 4)
Repeated k-foldSmall 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.

MethodPenaltyEffect
L2 (ridge)Sum of squared coefficientsShrinks all coefficients smoothly; stabilizes correlated features
L1 (lasso)Sum of absolute coefficientsDrives some coefficients exactly to zero; performs feature selection
Elastic netMix of L1 and L2Selection 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.

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:

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:

Common mistakes

Guided practice

Review questions

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.

← Previous Next →