博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Cross Validation done wrong
阅读量:6837 次
发布时间:2019-06-26

本文共 9809 字,大约阅读时间需要 32 分钟。

Cross validation is an essential tool in statistical learning  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 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 intok 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 MSE1MSE2,...MSEk. The cross validation estimate for the MSE is then computed by simply averaging these values:

 

CV(k)=1/ki=1kMSEi

 

 

This value is an estimate, say MSE^, of the real MSE and our goal is to make this estimate as accurate as possible.

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 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 .

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 has10.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  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 3122 and 830 that have a 0.36 and 0.39correlation with the output. At this point let's just drop all the other columns and use these two features to train a simpleLogisticRegression. We then use scikit-learn cross_val_score to compute MSE^ which in this case is equal to 0.33. Pretty good!

 

 

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 just0.33. The result is, as you can expect, wrong. But why?

The reason is rather counterintuitive and this is why this mistake is so common. 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 LogisticRegressionknew information in the test sets that were supposed to be hidden to it. In fact, when you are computing MSEi 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 theLogisticRegression because the feature selection has been appliedbefore the cross validation procedure started. The model knows something about the data highlighted in yellow that it shoulnd't know, its top correlated features.

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 MSE^ we estimated with the CV? The answer is no, and we got a much more reasonable MSE of0.53 that is much higher than the MSE^ of 0.33.

 

 

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 MSE^ of0.53 that confirms the data is randomly distributed.

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  and the classes inside the .

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

If you liked this post you should consider  on twitter.

Let me know your comments!

References

Posted on

10 thoughts on “Cross Validation done wrong”

    1. says:

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

      That way you can use the model selection tools of scikit-learn:

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

转载地址:http://clqkl.baihongyu.com/

你可能感兴趣的文章
关于GC的类型
查看>>
我的友情链接
查看>>
企业信息安全畅想
查看>>
spring 整合websoket(整理)
查看>>
Linux 之alias 命令别名
查看>>
windows-台式机添加硬盘后如何加载、格式化新的分区
查看>>
Jupyter on Kubernetes机器学习-MLflow
查看>>
iframe 父页面与子页面之间的方法的相互调用
查看>>
关于windows的进程处理(七)
查看>>
Commonly Hacked Ports
查看>>
一段话系列-QPS、TPS、PV是很么如何计算
查看>>
java关键字和保留字整合(不定期补充) 转自小码哥
查看>>
Log4J日志配置详解
查看>>
Exchange日常管理之二十二:配置保留策略
查看>>
数据库原理 - 序列5 - 事务是如何实现的? - Undo Log解析
查看>>
【笔记】与Android酱的第一周
查看>>
最先进数据中心都建在哪?
查看>>
一个jsp内嵌一个jsp
查看>>
将用户添加至sudoers列表
查看>>
MySQL用户管理、常用sql语句、数据库备份
查看>>