Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Validation

KTH JupyterHub Open In Colab Binder

The Importance of Independent Validation Sets in Machine Learning

In machine learning, the use of independent validation sets is crucial for evaluating model performance and avoiding one of the most common pitfalls: overfitting. Overfitting occurs when a model is trained to perform exceptionally well on the training data but fails to generalize to new, unseen data. This typically happens when the model is excessively complex for the given task or when it memorizes the noise and peculiarities of the training dataset instead of learning the underlying patterns.

An independent validation set helps to detect overfitting by providing a dataset that is separate from the training set, allowing for an unbiased evaluation of the model’s performance. Moreover, selecting the model that performs best on an independent validation set ensures that we are choosing a model that is most likely to generalize well to new data, rather than simply performing well on the training data.

To split data into a training and a validation set, scikit-learn provides the function train_test_split, which randomly partitions the data into a training set and a held-out set (which scikit-learn calls the test set). By default, train_test_split holds out 25% of the data, but this can be adjusted using the test_size parameter.

Example of Overfitting

Below, we create a small dataset of 10 data points, and compare three regression models of increasing complexity: a linear model, a quadratic model and an eighth-degree polynomial model.

Linear Model - Train Error: 2.90, Validation Error: 1.85
Quadratic Model - Train Error: 0.08, Validation Error: 0.28
High-Degree Model - Train Error: 0.00, Validation Error: 67.64
<Figure size 640x480 with 1 Axes>

The linear model misses the curvature of the data, and has a large error on both the training data (2.90) and the validation data (1.85); it is underfitting. The eighth-degree model has nine parameters but only seven training points, so it passes exactly through every training point (training error 0.00), but swings wildly between them and has a validation error of 67.64; it is overfitting. The quadratic model, which matches how the data were generated, has a low error on both sets.

Cross Validation to the Rescue

A problem with a separate validation set is that we have to reserve precious data for either training or validation, while we would like to use as much data as possible for both. Cross validation solves this by partitioning the data into multiple subsets, or folds, so that every data point is used both for training and for validation, and thereby estimates how well a model generalizes to new samples while still using all available data.

In k-fold cross validation, the dataset is split into k equally sized folds. The model is trained k times, each time using a different fold as the validation set and the remaining folds for training. The average of the validation metrics across all folds gives a more robust estimate of the model’s performance compared to using a single validation set.

Illustration of Three-Fold Cross Validation

Imagine we have a dataset with six data points, represented as A, B, C, D, E, F. In three-fold cross validation, we can split this dataset into three subsets, each containing two data points. For example:

Here is a code example illustrating three-fold cross validation with six data points. Note that the code shuffles the data before splitting it, so its folds differ from the ones listed above:

Fold 1: Training on [3 4 5 6], Validation on [1 2]
Fold 2: Training on [1 2 4 5], Validation on [3 6]
Fold 3: Training on [1 2 3 6], Validation on [4 5]

Cross Validation to detect overfitting

We now use three-fold cross validation with scikit-learn’s KFold to compare the second-degree and the eighth-degree polynomial models on the ten data points from above:

Mean cross-validated MSE, for 2nd degree: 0.23 and for 8th degree: 11003.98

The mean squared error (MSE) is calculated on the validation fold of each round, and averaged over the three folds. The second-degree model has a cross-validated MSE of 0.23, while the eighth-degree model, which has more parameters than there are training points in each round, has an MSE of about 11,000. Cross validation thus exposes the overfitting without setting aside a separate validation set.

Hyperparameter Selection

Hyperparameters are parameters of the machine learning model that are not learned from the training data but are instead set before training begins. Examples include the degree of a polynomial model, the strength of the regularization in ridge and LASSO regression, and the learning rate in gradient descent. Proper selection of hyperparameters is crucial to maximize a model’s performance. A common method for selecting them is grid search with cross validation, and nested cross validation lets us estimate how well the resulting model, including its hyperparameter selection, performs on new data.

Grid Search for Hyperparameter Tuning

Grid search is a brute-force method for finding the optimal hyperparameter values for a given model. It involves specifying a grid of hyperparameter values and then training and evaluating the model for each combination of parameters. The combination that yields the best performance on the validation set is selected as the final set of hyperparameters.

Let’s consider an example where we are training a LASSO regression model, and we want to determine the optimal value for the hyperparameter, α\alpha. LASSO regression is a linear model that includes L1 regularization, which helps to prevent overfitting by adding a penalty to the magnitude of the parameters, effectively setting some of them to zero. Here α\alpha plays the same role as the regularization parameter λ\lambda in the regularization chapter; scikit-learn calls it α\alpha. With grid search, we define a range of possible values for α\alpha and iterate over each value, training and evaluating the model at each step.

The following code uses scikit-learn’s GridSearchCV to perform a grid search over the regularization parameter of a LASSO regression model, on 100 data points generated from a second-order polynomial with Gaussian noise:

Best hyperparameters: {'lasso__alpha': 0.01}
Alpha: 0.01, parameters for model 1: [ 0.          0.10553842  1.23103587 -0.          0.1622308  -0.11625395]
Alpha: 0.1, parameters for model 2: [ 0.          0.          1.18498276 -0.          0.11636712 -0.        ]
Alpha: 1, parameters for model 3: [0.         0.         0.39640516 0.         0.         0.        ]
Alpha: 10, parameters for model 4: [0. 0. 0. 0. 0. 0.]
Alpha: 100, parameters for model 5: [0. 0. 0. 0. 0. 0.]

GridSearchCV runs a three-fold cross validation for each value of α\alpha in the grid, and selects the value with the lowest cross-validated MSE, here α=0.01\alpha = 0.01. Note that we shuffle the data before splitting it into folds. As our xx values are sorted, each fold would otherwise cover a contiguous third of the xx range, and the models would be judged on how well they extrapolate rather than on new points from the same range.

Nested Cross Validation

The cross-validated performance of the best hyperparameter value in a grid search is optimistic, as that value was selected precisely because it performed best on these validation folds. Using the same validation data both to tune the hyperparameters and to evaluate the model is thus a form of overfitting. To address this issue, nested cross validation is used.

In nested cross validation, there are two loops:

The following code performs nested cross validation with scikit-learn:

Nested cross-validated MSE: 0.21 (+/- 0.10)

Here the outer loop (outer_cv) splits the dataset into five folds, and for each of them the inner loop (inner_cv) runs a three-fold grid search on the remaining four folds. As the outer validation folds are never used to select α\alpha, the average MSE over them, 0.21, is a nearly unbiased estimate of the performance of the whole procedure, including the hyperparameter selection. Since the error is calculated on five separate validation folds, cross validation also tells us how much the performance varies, here with a standard deviation of 0.10 over the folds.

What you should know after reading this chapter

You should be able to:

  1. Explain what overfitting and underfitting are, and identify them from the training and validation errors of models of different complexity, such as a linear, a quadratic and an eighth-degree polynomial model.

  2. Explain why a model’s performance must be estimated on data that were not used to train it.

  3. Describe k-fold cross validation, and write out by hand how a small dataset, such as six data points in three folds, is split so that every point is used for validation exactly once.

  4. Explain the advantages of cross validation over a single validation set: all data are used for both training and validation, and the spread over the folds gives an estimate of the variance of the performance.

  5. Define a hyperparameter, contrast it with the parameters learned from the training data, and describe how grid search with cross validation selects a hyperparameter such as the LASSO regularization parameter α\alpha.

  6. Explain why the validation performance of the best setting in a grid search is optimistic, and describe how nested cross validation, with an inner loop for tuning and an outer loop for evaluation, avoids this.