Cross Validation done wrong

Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkedin
Share On Reddit
Contact us

Cross validation is an essential tool in statistical learning 1 to estimate the accuracy of your algorithm. Despite its great power it also exposes some fundamental risk when done wrong which may terribly bias your accuracy estimate.

In this blog post I'll demonstrate - using the Python scikit-learn2 framework - how to avoid the biggest and most common pitfall of cross validation in your experiments.

Theory first

Cross validation involves randomly dividing the set of observations into k groups (or folds) of approximately equal size. The first fold is treated as a validation set, and the machine learning algorithm is trained on the remaining k-1 folds. The mean squared error is then computed on the held-out fold. This procedure is repeated k times; each time, a different group of observations is treated as a validation set.

This process results in k estimates of the MSE quantity, namely MSE_1, MSE_2,...MSE_k. The cross validation estimate for the MSE is then computed by simply averaging these values:

CV_{(k)} = 1/k \sum_{i=1}^k MSE_i

This value is an estimate, say \hat{MSE}, of the real MSE and our goal is to make this estimate as accurate as possible. MSE is just one for the possible metrics you can estimate using cross validation but the results of this blog post are independent from the type of metric you use.

Hands on

Let's now have a look at one of the most typical mistakes when using cross validation. When cross validation is done wrong the result is that \hat{MSE} does not reflect its real value MSE. In other words, you may think that you just found a perfect machine learning algorithm with incredibly low MSE, while in reality you simply wrongly applied CV.

I'll first show you - hands on - a wrong application of cross validation and then we will fix it together. The code is also available as an IPython notebook on github.

Dataset generation

To make things simple let's first generate some random data and let's pretend that we want to build a machine learning algorithm to predict the outcome. I'll first generate a dataset of 100 entries. Each entry has 10.000 features. But, why so many? Well, to demonstrate our issue I need to generate some correlation between our inputs and output which is purely casual. You'll understand the why later in this post.

Feature selection

At this point we would like to know what are the features that are more useful to train our predictor. This is called feature selection. The simplest approach to do that is to find which of the 10.000 features in our input is mostly correlated the target. Using pandas this is very easy to do thanks to the corr() function. We run corr() on our dataframe, we order the correlation values, and we pick the first two features.

Start the training

Great! Out of the 10.000 features we have been able to select two of them, i.e. feature number 8487 and 3555 that have a 0.42 and 0.39 correlation with the output. At this point let's just drop all the other columns and use these two features to train a simple LogisticRegression. We then use scikit-learn cross_val_score to compute \hat{MSE} which in this case is equal to 0.249. Pretty good!

Note [1]: I am using MSE here to evaluate the quality of the logistic regression, but you should probably consider using a Chi-squared test. The interpretation of the results that follows is equivalent.

Note [2]: By default scikit-learn use Stratified KFold3 where the folds are made by preserving the percentage of samples for each class.

Knowledge leaking

According to the previous estimate we built a system that can predict a random noise target from a random noise input with a MSE of just 0.249. The result is, as you can expect, wrong. But why?

The reason is rather counterintuitive and this is why this mistake is so common4. When we applied the feature selection we used information from both the training set and the test sets used for the cross validation, i.e. the correlation values. As a consequence our LogisticRegression knew information in the test sets that were supposed to be hidden to it. In fact, when you are computing MSE_i in the i-th iteration of the cross validation you should be using only the information on the training fold, and nothing should come from the test fold. In our case the model did indeed have information from the test fold, i.e. the top correlated features. I think the term knowledge leaking express this concept fairly well.

The schema that follows shows you how the knowledge leaked into the LogisticRegression because the feature selection has been applied before the cross validation procedure started. The model knows something about the data highlighted in yellow that it shoulnd't know, its top correlated features.

The exposed knowledge leaking. The LogisticRegression knows the top correlated features of the entire dataset (hence including test folds) because of the initial correlation operation, whilst it should be exposed only to the training fold information.
Figure 1. The exposed knowledge leaking. The LogisticRegression knows the top correlated features of the entire dataset (hence including test folds) because of the initial correlation operation, whilst it should be exposed only to the training fold information.

Proof that our model is biased

To check that we were actually wrong let's do the following:
* Take out a portion of the data set (take_out_set).
* Train the LogisticRegression on the remaining data using the same feature selection we did before.
* After the training is done check the MSE on the take_out_set.

Is the MSE on the take_out_set similar to the \hat{MSE} we estimated with the CV? The answer is no, and we got a much more reasonable MSE of 0.53 that is much higher than the \hat{MSE} of 0.249.

Cross validation done right

In the previous section we have seen that if you inject test knowledge in your model your cross validation procedure will be biased. To avoid this let's compute the features correlation during each cross validation batch. The difference is that now the features correlation will use only the information in the training fold instead of the entire dataset. That's the key insight causing the bias we saw previously. The following graph shows you the revisited procedure. This time we got a realistic \hat{MSE} of 0.44 that confirms the data is randomly distributed.

Figure 2.  Revisited cross validation workflow with the correlation step performed for each of the K fold train/test data folds.
Figure 2. Revisited cross validation workflow with the correlation step performed for each of the K train/test folds.

Conclusion

We have seen how doing features selection at the wrong step can terribly bias the MSE estimate of your machine learning algorithm. We have also seen how to correctly apply cross validation by simply moving one step down the features selection such that the knowledge from the test data does not leak in our learning procedure.

If you want to make sure you don't leak info across the train and test set scikit learn gives you additional extra tools like the feature selection pipeline5 and the classes inside the feature selection module6.

Finally, if you want know more about cross validation and its tradeoffs both R. Kohavi7 and Y. Bengio with Y. Grandvalet8 wrote on this topic.

If you liked this post you should consider following me on twitter.
Let me know your comments!

References

  1. Lecture 1 on cross validation - Statistical Learning @ Stanford
  2. Scikit-learn framework
  3. Stratified KFold Documentation
  4. Lecture 2 on cross validation - Statistical Learning @ Stanford
  5. Scikit-learn feature selection pipeline
  6. Scikit-learn feature selection modules
  7. R. Kohavi. A study of cross-validation and bootstrap for accuracy estimation and model selection
  8. Y. Bengio and Y. Grandvalet. No unbiased estimator of the variance of k-fold cross-validation

28 thoughts on “Cross Validation done wrong

  1. To do feature selection inside a cross-validation loop, you should really be using the feature selection objects inside a pipeline:

    http://scikit-learn.org/stable/auto_examples/feature_selection/feature_selection_pipeline.html

    http://scikit-learn.org/stable/modules/feature_selection.html

    That way you can use the model selection tools of scikit-learn:
    http://scikit-learn.org/stable/modules/model_evaluation.html

    And you are certain that you won't be leaking info across train and test sets.

  2. Thanks for this - I enjoyed reading it. I think it would help to set your random seed in the beginning, though so that people running your notebook end up with the same data as you...

  3. Nice write-up!
    Maybe add a short sentence about stratified k-fold cross-validation (default for classification estimators in scikit-learn).
    Another note: If you want to evaluate the goodness of fit of a logistic regression model (in contrast to predictive performance measures like accuracy, classification error etc.), isn't it more appropriate to use chi-square or mean deviance rather than mean squared error?

    1. Thank you for you comment Sebastian. I think you are right, a chi-square is more appropriate. I'd say that for clarity using the MSE is more effective (everyone knows it), but I'll point that out in the code for people to be aware.

  4. Very interesting read!

    I would like to stress another requirement for the application of cross validation though that you may want to add: statistical independence of the samples in the data-set.

    A quick example: Two scenarios
    1) classification of images, randomly taken from the web
    2) classification of images, extracted from a video stream
    In the first scenario the images are independent of each other and we can apply cross validation to obtain a reliable performance of our system. However, the situation changes in the second setting: Subsequent images from a video are highly correlated and therefore not statistically independent anymore!

    Say we extracted 100 images from the video, split those into 10 folds, and run through a cross-validation. If we predict an image i, what is the chance that the (very similar) adjacent frames i-1 or i+1 are in the training-set? It is 99%! In the second setting we are basically only testing how well we can preserve the pairwise similarity of images, which does not generalise at all to any realistic setting and biases our performance, our choice of features and choice of classification approach. This is a significant issue that many people are not aware of!

    We just got a paper accepted in Ubicomp 2015 on this bias of cross-validation in time-series data and how it can be alleviated through a slightly adapted approach. I can't share a link yet as the proceedings are not yet online, but drop me an email though if you are interested.

    1. That's a very nice example, Nils,
      but if you are using logistic regression like shown in this post, don't you make the assumptions that samples are i.i.d. anyway (i.e., in the likelihood function / or the reversed cost function if you will)? Aside from violated assumptions during model training, I think this -- samples from different populations -- is a problem in general, and k-fold cross validation is probably less affected than the holdout method.

      I am looking forward to give your paper a read, this sounds interesting!

      Cheers,
      Sebastian

    2. I would like to read that paper. Can you send it to alind_sap@yahoo.com . I am currently in the process of doing classification from images coming through video stream and was thinking how to appropriately test/Cross-Validate it. Should I take a totally new stream etc.

    3. Great post. Nils, I will be interested in reading your article on cross validation and time series data (bikiengasalif@yahoo.fr).
      Cheers,

  5. Sure, most approaches in ML assume that the data is i.i.d. Lack of independence doesn't lead to a bloated, biased performance of the methods though. Instead their performance is often disappointingly bad, as you waste a lot of parameters in modeling invariances or symmetries (e.g. translation in images). This is one of the reasons why convolutional networks work much better than fully connected networks in computer vision tasks.

    You are right about the difference in populations being crucial in the evaluation. But in cases of non-i.i.d. data I would actually recommend hold-out validation over cross-validation. It all depends on how you select your folds. For example, using the last 20 images from the video example above as test-set wouldn't suffer from the same degree of bias than cross-validation, as subsequent images are kept together in the same set.

    Cheers

    NilsReference

    1. " For example, using the last 20 images from the video example above as test-set wouldn't suffer from the same degree of bias than cross-validation, as subsequent images are kept together in the same set." I agree in this case, I didn't think about the time-series example specifically but assume that you were shuffling the training dataset prior to splitting.

  6. Thanks for writing this. I'd like to comment that your "Theory first" section may confuse newcomers a little, since you make it sound as if cross-validation is intrinsically tied to MSE, whereas you can use it for various figures of merit. So, even if you want to use MSE as a "simple" example (though for a newcomer it might not be obvious), perhaps you could make it clearer that MSE is just one possible measurement?

    (Also I agree that stratified crossval would be the next thing to introduce. A future post maybe...)

    1. Hello Michael, thank you for your question.

      In this particular example the learning automatically select the most correlated features so don't need to choose between any of them.

      In a real world setting where you want to select some features it is important that you take an hold-out set.

      The hold-out set will be used to asses if the performance estimated by the CV has been biased by your feature selection (like in the example I gave here).

      Make sense?

  7. Nice post and very interesting!

    After cross-validation we have got ten different models (k=10) and probably with a different feature selection. Which of these 10 models should be considered as the final model.

    Thanks in advanced and sorry if it is a noob question.

    1. Hello Pedro, thank you for your question!
      it's usually a good advice to select more than one model and average their predictions. In this example we got 10 models and we may decide to pick up the top 3 performers. This is because each of these models are biased towards one of the subsets they have been trained on and when you will see new data you actually don't know which of them will perform best. Make sense?

  8. Hi Alfredo
    Can you please elaborate some more on the question that Michael asked. Which features to take in the final model?

    1. Hi Vivek, thank you for your question.

      the top performing model at the end of the CV will have some features selected. You can pick these.

      If you want to be more conservative, you can look at the top 20% performers and see what features they selected and take these.

      Remember that CV is a method to estimate the performance of a model. This includes both the feature selection procedure and the model training on these features.

      So at the end you don't just walk away with the top features, but both feature and the parameters of the Logistic regression associated with them.

      Does it make sense?

Leave a Reply

Your email address will not be published. Required fields are marked *

Answer the question * Time limit is exhausted. Please reload CAPTCHA.