3.1.Cross-validation: evaluating estimator performance#

Learning the parameters of a prediction function and testing it on thesame data is a methodological mistake: a model that would just repeatthe labels of the samples that it has just seen would have a perfectscore but would fail to predict anything useful on yet-unseen data.This situation is calledoverfitting.To avoid it, it is common practice when performinga (supervised) machine learning experimentto hold out part of the available data as atest setX_test,y_test.Note that the word “experiment” is not intendedto denote academic use only,because even in commercial settingsmachine learning usually starts out experimentally.Here is a flowchart of typical cross validation workflow in model training.The best parameters can be determined bygrid search techniques.

Grid Search Workflow

In scikit-learn a random split into training and test setscan be quickly computed with thetrain_test_split helper function.Let’s load the iris data set to fit a linear support vector machine on it:

>>>importnumpyasnp>>>fromsklearn.model_selectionimporttrain_test_split>>>fromsklearnimportdatasets>>>fromsklearnimportsvm>>>X,y=datasets.load_iris(return_X_y=True)>>>X.shape,y.shape((150, 4), (150,))

We can now quickly sample a training set while holding out 40% of thedata for testing (evaluating) our classifier:

>>>X_train,X_test,y_train,y_test=train_test_split(...X,y,test_size=0.4,random_state=0)>>>X_train.shape,y_train.shape((90, 4), (90,))>>>X_test.shape,y_test.shape((60, 4), (60,))>>>clf=svm.SVC(kernel='linear',C=1).fit(X_train,y_train)>>>clf.score(X_test,y_test)0.96

When evaluating different settings (“hyperparameters”) for estimators,such as theC setting that must be manually set for an SVM,there is still a risk of overfittingon the test setbecause the parameters can be tweaked until the estimator performs optimally.This way, knowledge about the test set can “leak” into the modeland evaluation metrics no longer report on generalization performance.To solve this problem, yet another part of the dataset can be held outas a so-called “validation set”: training proceeds on the training set,after which evaluation is done on the validation set,and when the experiment seems to be successful,final evaluation can be done on the test set.

However, by partitioning the available data into three sets,we drastically reduce the number of sampleswhich can be used for learning the model,and the results can depend on a particular random choice for the pair of(train, validation) sets.

A solution to this problem is a procedure calledcross-validation(CV for short).A test set should still be held out for final evaluation,but the validation set is no longer needed when doing CV.In the basic approach, calledk-fold CV,the training set is split intok smaller sets(other approaches are described below,but generally follow the same principles).The following procedure is followed for each of thek “folds”:

  • A model is trained using\(k-1\) of the folds as training data;

  • the resulting model is validated on the remaining part of the data(i.e., it is used as a test set to compute a performance measuresuch as accuracy).

The performance measure reported byk-fold cross-validationis then the average of the values computed in the loop.This approach can be computationally expensive,but does not waste too much data(as is the case when fixing an arbitrary validation set),which is a major advantage in problems such as inverse inferencewhere the number of samples is very small.

A depiction of a 5 fold cross validation on a training set, while holding out a test set.

3.1.1.Computing cross-validated metrics#

The simplest way to use cross-validation is to call thecross_val_score helper function on the estimator and the dataset.

The following example demonstrates how to estimate the accuracy of a linearkernel support vector machine on the iris dataset by splitting the data, fittinga model and computing the score 5 consecutive times (with different splits eachtime):

>>>fromsklearn.model_selectionimportcross_val_score>>>clf=svm.SVC(kernel='linear',C=1,random_state=42)>>>scores=cross_val_score(clf,X,y,cv=5)>>>scoresarray([0.96, 1. , 0.96, 0.96, 1. ])

The mean score and the standard deviation are hence given by:

>>>print("%0.2f accuracy with a standard deviation of%0.2f"%(scores.mean(),scores.std()))0.98 accuracy with a standard deviation of 0.02

By default, the score computed at each CV iteration is thescoremethod of the estimator. It is possible to change this by using thescoring parameter:

>>>fromsklearnimportmetrics>>>scores=cross_val_score(...clf,X,y,cv=5,scoring='f1_macro')>>>scoresarray([0.96, 1., 0.96, 0.96, 1.])

SeeThe scoring parameter: defining model evaluation rules for details.In the case of the Iris dataset, the samples are balanced across targetclasses hence the accuracy and the F1-score are almost equal.

When thecv argument is an integer,cross_val_score uses theKFold orStratifiedKFold strategies by default, the latterbeing used if the estimator derives fromClassifierMixin.

It is also possible to use other cross validation strategies by passing a crossvalidation iterator instead, for instance:

>>>fromsklearn.model_selectionimportShuffleSplit>>>n_samples=X.shape[0]>>>cv=ShuffleSplit(n_splits=5,test_size=0.3,random_state=0)>>>cross_val_score(clf,X,y,cv=cv)array([0.977, 0.977, 1., 0.955, 1.])

Another option is to use an iterable yielding (train, test) splits as arrays ofindices, for example:

>>>defcustom_cv_2folds(X):...n=X.shape[0]...i=1...whilei<=2:...idx=np.arange(n*(i-1)/2,n*i/2,dtype=int)...yieldidx,idx...i+=1...>>>custom_cv=custom_cv_2folds(X)>>>cross_val_score(clf,X,y,cv=custom_cv)array([1.        , 0.973])
Data transformation with held-out data#

Just as it is important to test a predictor on data held-out fromtraining, preprocessing (such as standardization, feature selection, etc.)and similardata transformations similarly shouldbe learnt from a training set and applied to held-out data for prediction:

>>>fromsklearnimportpreprocessing>>>X_train,X_test,y_train,y_test=train_test_split(...X,y,test_size=0.4,random_state=0)>>>scaler=preprocessing.StandardScaler().fit(X_train)>>>X_train_transformed=scaler.transform(X_train)>>>clf=svm.SVC(C=1).fit(X_train_transformed,y_train)>>>X_test_transformed=scaler.transform(X_test)>>>clf.score(X_test_transformed,y_test)0.9333

APipeline makes it easier to composeestimators, providing this behavior under cross-validation:

>>>fromsklearn.pipelineimportmake_pipeline>>>clf=make_pipeline(preprocessing.StandardScaler(),svm.SVC(C=1))>>>cross_val_score(clf,X,y,cv=cv)array([0.977, 0.933, 0.955, 0.933, 0.977])

SeePipelines and composite estimators.

3.1.1.1.The cross_validate function and multiple metric evaluation#

Thecross_validate function differs fromcross_val_score intwo ways:

  • It allows specifying multiple metrics for evaluation.

  • It returns a dict containing fit-times, score-times(and optionally training scores, fitted estimators, train-test split indices)in addition to the test score.

For single metric evaluation, where the scoring parameter is a string,callable or None, the keys will be -['test_score','fit_time','score_time']

And for multiple metric evaluation, the return value is a dict with thefollowing keys -['test_<scorer1_name>','test_<scorer2_name>','test_<scorer...>','fit_time','score_time']

return_train_score is set toFalse by default to save computation time.To evaluate the scores on the training set as well you need to set it toTrue. You may also retain the estimator fitted on each training set bysettingreturn_estimator=True. Similarly, you may setreturn_indices=True to retain the training and testing indices used to splitthe dataset into train and test sets for each cv split.

The multiple metrics can be specified either as a list, tuple or set ofpredefined scorer names:

>>>fromsklearn.model_selectionimportcross_validate>>>fromsklearn.metricsimportrecall_score>>>scoring=['precision_macro','recall_macro']>>>clf=svm.SVC(kernel='linear',C=1,random_state=0)>>>scores=cross_validate(clf,X,y,scoring=scoring)>>>sorted(scores.keys())['fit_time', 'score_time', 'test_precision_macro', 'test_recall_macro']>>>scores['test_recall_macro']array([0.96, 1., 0.96, 0.96, 1.])

Or as a dict mapping scorer name to a predefined or custom scoring function:

>>>fromsklearn.metricsimportmake_scorer>>>scoring={'prec_macro':'precision_macro',...'rec_macro':make_scorer(recall_score,average='macro')}>>>scores=cross_validate(clf,X,y,scoring=scoring,...cv=5,return_train_score=True)>>>sorted(scores.keys())['fit_time', 'score_time', 'test_prec_macro', 'test_rec_macro', 'train_prec_macro', 'train_rec_macro']>>>scores['train_rec_macro']array([0.97, 0.97, 0.99, 0.98, 0.98])

Here is an example ofcross_validate using a single metric:

>>>scores=cross_validate(clf,X,y,...scoring='precision_macro',cv=5,...return_estimator=True)>>>sorted(scores.keys())['estimator', 'fit_time', 'score_time', 'test_score']

3.1.1.2.Obtaining predictions by cross-validation#

The functioncross_val_predict has a similar interface tocross_val_score, but returns, for each element in the input, theprediction that was obtained for that element when it was in the test set. Onlycross-validation strategies that assign all elements to a test set exactly oncecan be used (otherwise, an exception is raised).

Warning

Note on inappropriate usage of cross_val_predict

The result ofcross_val_predict may be different from thoseobtained usingcross_val_score as the elements are grouped indifferent ways. The functioncross_val_score takes an averageover cross-validation folds, whereascross_val_predict simplyreturns the labels (or probabilities) from several distinct modelsundistinguished. Thus,cross_val_predict is not an appropriatemeasure of generalization error.

The functioncross_val_predict is appropriate for:
  • Visualization of predictions obtained from different models.

  • Model blending: When predictions of one supervised estimator are used totrain another estimator in ensemble methods.

The available cross validation iterators are introduced in the followingsection.

Examples

3.1.2.Cross validation iterators#

The following sections list utilities to generate indicesthat can be used to generate dataset splits according to different crossvalidation strategies.

3.1.2.1.Cross-validation iterators for i.i.d. data#

Assuming that some data is Independent and Identically Distributed (i.i.d.) ismaking the assumption that all samples stem from the same generative processand that the generative process is assumed to have no memory of past generatedsamples.

The following cross-validators can be used in such cases.

Note

While i.i.d. data is a common assumption in machine learning theory, it rarelyholds in practice. If one knows that the samples have been generated using atime-dependent process, it is safer touse atime-series aware cross-validation scheme.Similarly, if we know that the generative process has a group structure(samples collected from different subjects, experiments, measurementdevices), it is safer to usegroup-wise cross-validation.

3.1.2.1.1.K-fold#

KFold divides all the samples in\(k\) groups of samples,called folds (if\(k = n\), this is equivalent to theLeave OneOut strategy), of equal sizes (if possible). The prediction function islearned using\(k - 1\) folds, and the fold left out is used for test.

Example of 2-fold cross-validation on a dataset with 4 samples:

>>>importnumpyasnp>>>fromsklearn.model_selectionimportKFold>>>X=["a","b","c","d"]>>>kf=KFold(n_splits=2)>>>fortrain,testinkf.split(X):...print("%s%s"%(train,test))[2 3] [0 1][0 1] [2 3]

Here is a visualization of the cross-validation behavior. Note thatKFold is not affected by classes or groups.

../_images/sphx_glr_plot_cv_indices_006.png

Each fold is constituted by two arrays: the first one is related to thetraining set, and the second one to thetest set.Thus, one can create the training/test sets using numpy indexing:

>>>X=np.array([[0.,0.],[1.,1.],[-1.,-1.],[2.,2.]])>>>y=np.array([0,1,0,1])>>>X_train,X_test,y_train,y_test=X[train],X[test],y[train],y[test]

3.1.2.1.2.Repeated K-Fold#

RepeatedKFold repeatsKFold\(n\) times, producing different splits ineach repetition.

Example of 2-fold K-Fold repeated 2 times:

>>>importnumpyasnp>>>fromsklearn.model_selectionimportRepeatedKFold>>>X=np.array([[1,2],[3,4],[1,2],[3,4]])>>>random_state=12883823>>>rkf=RepeatedKFold(n_splits=2,n_repeats=2,random_state=random_state)>>>fortrain,testinrkf.split(X):...print("%s%s"%(train,test))...[2 3] [0 1][0 1] [2 3][0 2] [1 3][1 3] [0 2]

Similarly,RepeatedStratifiedKFold repeatsStratifiedKFold\(n\) timeswith different randomization in each repetition.

3.1.2.1.3.Leave One Out (LOO)#

LeaveOneOut (or LOO) is a simple cross-validation. Each learningset is created by taking all the samples except one, the test set beingthe sample left out. Thus, for\(n\) samples, we have\(n\) differenttraining sets and\(n\) different test sets. This cross-validationprocedure does not waste much data as only one sample is removed from thetraining set:

>>>fromsklearn.model_selectionimportLeaveOneOut>>>X=[1,2,3,4]>>>loo=LeaveOneOut()>>>fortrain,testinloo.split(X):...print("%s%s"%(train,test))[1 2 3] [0][0 2 3] [1][0 1 3] [2][0 1 2] [3]

Potential users of LOO for model selection should weigh a few known caveats.When compared with\(k\)-fold cross validation, one builds\(n\) modelsfrom\(n\) samples instead of\(k\) models, where\(n > k\).Moreover, each is trained on\(n - 1\) samples rather than\((k-1) n / k\). In both ways, assuming\(k\) is not too largeand\(k < n\), LOO is more computationally expensive than\(k\)-foldcross validation.

In terms of accuracy, LOO often results in high variance as an estimator for thetest error. Intuitively, since\(n - 1\) ofthe\(n\) samples are used to build each model, models constructed fromfolds are virtually identical to each other and to the model built from theentire training set.

However, if the learning curve is steep for the training size in question,then 5 or 10-fold cross validation can overestimate the generalization error.

As a general rule, most authors and empirical evidence suggest that 5 or 10-foldcross validation should be preferred to LOO.

References#

3.1.2.1.4.Leave P Out (LPO)#

LeavePOut is very similar toLeaveOneOut as it creates allthe possible training/test sets by removing\(p\) samples from the completeset. For\(n\) samples, this produces\({n \choose p}\) train-testpairs. UnlikeLeaveOneOut andKFold, the test sets willoverlap for\(p > 1\).

Example of Leave-2-Out on a dataset with 4 samples:

>>>fromsklearn.model_selectionimportLeavePOut>>>X=np.ones(4)>>>lpo=LeavePOut(p=2)>>>fortrain,testinlpo.split(X):...print("%s%s"%(train,test))[2 3] [0 1][1 3] [0 2][1 2] [0 3][0 3] [1 2][0 2] [1 3][0 1] [2 3]

3.1.2.1.5.Random permutations cross-validation a.k.a. Shuffle & Split#

TheShuffleSplit iterator will generate a user defined number ofindependent train / test dataset splits. Samples are first shuffled andthen split into a pair of train and test sets.

It is possible to control the randomness for reproducibility of theresults by explicitly seeding therandom_state pseudo random numbergenerator.

Here is a usage example:

>>>fromsklearn.model_selectionimportShuffleSplit>>>X=np.arange(10)>>>ss=ShuffleSplit(n_splits=5,test_size=0.25,random_state=0)>>>fortrain_index,test_indexinss.split(X):...print("%s%s"%(train_index,test_index))[9 1 6 7 3 0 5] [2 8 4][2 9 8 0 6 7 4] [3 5 1][4 5 1 0 6 9 7] [2 3 8][2 7 5 8 0 3 4] [6 1 9][4 1 0 6 8 9 3] [5 2 7]

Here is a visualization of the cross-validation behavior. Note thatShuffleSplit is not affected by classes or groups.

../_images/sphx_glr_plot_cv_indices_008.png

ShuffleSplit is thus a good alternative toKFold crossvalidation that allows a finer control on the number of iterations andthe proportion of samples on each side of the train / test split.

3.1.2.2.Cross-validation iterators with stratification based on class labels#

Some classification tasks can naturally exhibit rare classes: for instance,there could be orders of magnitude more negative observations than positiveobservations (e.g. medical screening, fraud detection, etc). As a result,cross-validation splitting can generate train or validation folds without anyoccurrence of a particular class. This typically leads to undefinedclassification metrics (e.g. ROC AUC), exceptions raised when attempting tocallfit or missing columns in the output of thepredict_proba ordecision_function methods of multiclass classifiers trained on differentfolds.

To mitigate such problems, splitters such asStratifiedKFold andStratifiedShuffleSplit implement stratified sampling to ensure thatrelative class frequencies are approximately preserved in each fold.

Note

Stratified sampling was introduced in scikit-learn to workaround theaforementioned engineering problems rather than solve a statistical one.

Stratification makes cross-validation folds more homogeneous, and as a resulthides some of the variability inherent to fitting models with a limitednumber of observations.

As a result, stratification can artificially shrink the spread of the metricmeasured across cross-validation iterations: the inter-fold variability doesno longer reflect the uncertainty in the performance of classifiers in thepresence of rare classes.

3.1.2.2.1.Stratified K-fold#

StratifiedKFold is a variation ofK-fold which returnsstratifiedfolds: each set contains approximately the same percentage of samples of eachtarget class as the complete set.

Here is an example of stratified 3-fold cross-validation on a dataset with 50 samples fromtwo unbalanced classes. We show the number of samples in each class and compare withKFold.

>>>fromsklearn.model_selectionimportStratifiedKFold,KFold>>>importnumpyasnp>>>X,y=np.ones((50,1)),np.hstack(([0]*45,[1]*5))>>>skf=StratifiedKFold(n_splits=3)>>>fortrain,testinskf.split(X,y):...print('train -{}   |   test -{}'.format(...np.bincount(y[train]),np.bincount(y[test])))train -  [30  3]   |   test -  [15  2]train -  [30  3]   |   test -  [15  2]train -  [30  4]   |   test -  [15  1]>>>kf=KFold(n_splits=3)>>>fortrain,testinkf.split(X,y):...print('train -{}   |   test -{}'.format(...np.bincount(y[train]),np.bincount(y[test])))train -  [28  5]   |   test -  [17]train -  [28  5]   |   test -  [17]train -  [34]   |   test -  [11  5]

We can see thatStratifiedKFold preserves the class ratios(approximately 1 / 10) in both train and test datasets.

Here is a visualization of the cross-validation behavior.

../_images/sphx_glr_plot_cv_indices_009.png

RepeatedStratifiedKFold can be used to repeat Stratified K-Fold n timeswith different randomization in each repetition.

3.1.2.2.2.Stratified Shuffle Split#

StratifiedShuffleSplit is a variation ofShuffleSplit, which returnsstratified splits,i.e. which creates splits by preserving the samepercentage for each target class as in the complete set.

Here is a visualization of the cross-validation behavior.

../_images/sphx_glr_plot_cv_indices_012.png

3.1.2.3.Predefined fold-splits / Validation-sets#

For some datasets, a pre-defined split of the data into training- andvalidation fold or into several cross-validation folds alreadyexists. UsingPredefinedSplit it is possible to use these foldse.g. when searching for hyperparameters.

For example, when using a validation set, set thetest_fold to 0 for allsamples that are part of the validation set, and to -1 for all other samples.

3.1.2.4.Cross-validation iterators for grouped data#

The i.i.d. assumption is broken if the underlying generative process yieldsgroups of dependent samples.

Such a grouping of data is domain specific. An example would be when there ismedical data collected from multiple patients, with multiple samples taken fromeach patient. And such data is likely to be dependent on the individual group.In our example, the patient id for each sample will be its group identifier.

In this case we would like to know if a model trained on a particular set ofgroups generalizes well to the unseen groups. To measure this, we need toensure that all the samples in the validation fold come from groups that arenot represented at all in the paired training fold.

The following cross-validation splitters can be used to do that.The grouping identifier for the samples is specified via thegroupsparameter.

3.1.2.4.1.Group K-fold#

GroupKFold is a variation of K-fold which ensures that the same group isnot represented in both testing and training sets. For example if the data isobtained from different subjects with several samples per-subject and if themodel is flexible enough to learn from highly person specific features itcould fail to generalize to new subjects.GroupKFold makes it possibleto detect this kind of overfitting situations.

Imagine you have three subjects, each with an associated number from 1 to 3:

>>>fromsklearn.model_selectionimportGroupKFold>>>X=[0.1,0.2,2.2,2.4,2.3,4.55,5.8,8.8,9,10]>>>y=["a","b","b","b","c","c","c","d","d","d"]>>>groups=[1,1,1,2,2,2,3,3,3,3]>>>gkf=GroupKFold(n_splits=3)>>>fortrain,testingkf.split(X,y,groups=groups):...print("%s%s"%(train,test))[0 1 2 3 4 5] [6 7 8 9][0 1 2 6 7 8 9] [3 4 5][3 4 5 6 7 8 9] [0 1 2]

Each subject is in a different testing fold, and the same subject is never inboth testing and training. Notice that the folds do not have exactly the samesize due to the imbalance in the data. If class proportions must be balancedacross folds,StratifiedGroupKFold is a better option.

Here is a visualization of the cross-validation behavior.

../_images/sphx_glr_plot_cv_indices_007.png

Similar toKFold, the test sets fromGroupKFold will form acomplete partition of all the data.

WhileGroupKFold attempts to place the same number of samples in eachfold whenshuffle=False, whenshuffle=True it attempts to place an equalnumber of distinct groups in each fold (but does not account for group sizes).

3.1.2.4.2.StratifiedGroupKFold#

StratifiedGroupKFold is a cross-validation scheme that combines bothStratifiedKFold andGroupKFold. The idea is to try topreserve the distribution of classes in each split while keeping each groupwithin a single split. That might be useful when you have an unbalanceddataset so that using justGroupKFold might produce skewed splits.

Example:

>>>fromsklearn.model_selectionimportStratifiedGroupKFold>>>X=list(range(18))>>>y=[1]*6+[0]*12>>>groups=[1,2,3,3,4,4,1,1,2,2,3,4,5,5,5,6,6,6]>>>sgkf=StratifiedGroupKFold(n_splits=3)>>>fortrain,testinsgkf.split(X,y,groups=groups):...print("%s%s"%(train,test))[ 0  2  3  4  5  6  7 10 11 15 16 17] [ 1  8  9 12 13 14][ 0  1  4  5  6  7  8  9 11 12 13 14] [ 2  3 10 15 16 17][ 1  2  3  8  9 10 12 13 14 15 16 17] [ 0  4  5  6  7 11]
Implementation notes#
  • With the current implementation full shuffle is not possible in mostscenarios. When shuffle=True, the following happens:

    1. All groups are shuffled.

    2. Groups are sorted by standard deviation of classes using stable sort.

    3. Sorted groups are iterated over and assigned to folds.

    That means that only groups with the same standard deviation of classdistribution will be shuffled, which might be useful when each group has onlya single class.

  • The algorithm greedily assigns each group to one of n_splits test sets,choosing the test set that minimises the variance in class distributionacross test sets. Group assignment proceeds from groups with highest tolowest variance in class frequency, i.e. large groups peaked on one or fewclasses are assigned first.

  • This split is suboptimal in a sense that it might produce imbalanced splitseven if perfect stratification is possible. If you have relatively closedistribution of classes in each group, usingGroupKFold is better.

Here is a visualization of cross-validation behavior for uneven groups:

../_images/sphx_glr_plot_cv_indices_005.png

3.1.2.4.3.Leave One Group Out#

LeaveOneGroupOut is a cross-validation scheme where each split holdsout samples belonging to one specific group. Group information isprovided via an array that encodes the group of each sample.

Each training set is thus constituted by all the samples except the onesrelated to a specific group. This is the same asLeavePGroupsOut withn_groups=1 and the same asGroupKFold withn_splits equal to thenumber of unique labels passed to thegroups parameter.

For example, in the cases of multiple experiments,LeaveOneGroupOutcan be used to create a cross-validation based on the different experiments:we create a training set using the samples of all the experiments except one:

>>>fromsklearn.model_selectionimportLeaveOneGroupOut>>>X=[1,5,10,50,60,70,80]>>>y=[0,1,1,2,2,2,2]>>>groups=[1,1,2,2,3,3,3]>>>logo=LeaveOneGroupOut()>>>fortrain,testinlogo.split(X,y,groups=groups):...print("%s%s"%(train,test))[2 3 4 5 6] [0 1][0 1 4 5 6] [2 3][0 1 2 3] [4 5 6]

Another common application is to use time information: for instance thegroups could be the year of collection of the samples and thus allowfor cross-validation against time-based splits.

3.1.2.4.4.Leave P Groups Out#

LeavePGroupsOut is similar toLeaveOneGroupOut, but removessamples related to\(P\) groups for each training/test set. All possiblecombinations of\(P\) groups are left out, meaning test sets will overlapfor\(P>1\).

Example of Leave-2-Group Out:

>>>fromsklearn.model_selectionimportLeavePGroupsOut>>>X=np.arange(6)>>>y=[1,1,1,2,2,2]>>>groups=[1,1,2,2,3,3]>>>lpgo=LeavePGroupsOut(n_groups=2)>>>fortrain,testinlpgo.split(X,y,groups=groups):...print("%s%s"%(train,test))[4 5] [0 1 2 3][2 3] [0 1 4 5][0 1] [2 3 4 5]

3.1.2.4.5.Group Shuffle Split#

TheGroupShuffleSplit iterator behaves as a combination ofShuffleSplit andLeavePGroupsOut, and generates asequence of randomized partitions in which a subset of groups are heldout for each split. Each train/test split is performed independently meaningthere is no guaranteed relationship between successive test sets.

Here is a usage example:

>>>fromsklearn.model_selectionimportGroupShuffleSplit>>>X=[0.1,0.2,2.2,2.4,2.3,4.55,5.8,0.001]>>>y=["a","b","b","b","c","c","c","a"]>>>groups=[1,1,2,2,3,3,4,4]>>>gss=GroupShuffleSplit(n_splits=4,test_size=0.5,random_state=0)>>>fortrain,testingss.split(X,y,groups=groups):...print("%s%s"%(train,test))...[0 1 2 3] [4 5 6 7][2 3 6 7] [0 1 4 5][2 3 4 5] [0 1 6 7][4 5 6 7] [0 1 2 3]

Here is a visualization of the cross-validation behavior.

../_images/sphx_glr_plot_cv_indices_011.png

This class is useful when the behavior ofLeavePGroupsOut isdesired, but the number of groups is large enough that generating allpossible partitions with\(P\) groups withheld would be prohibitivelyexpensive. In such a scenario,GroupShuffleSplit providesa random sample (with replacement) of the train / test splitsgenerated byLeavePGroupsOut.

3.1.2.5.Using cross-validation iterators to split train and test#

The above group cross-validation functions may also be useful for splitting adataset into training and testing subsets. Note that the conveniencefunctiontrain_test_split is a wrapper aroundShuffleSplitand thus only allows for stratified splitting (using the class labels)and cannot account for groups.

To perform the train and test split, use the indices for the train and testsubsets yielded by the generator output by thesplit() method of thecross-validation splitter. For example:

>>>importnumpyasnp>>>fromsklearn.model_selectionimportGroupShuffleSplit>>>X=np.array([0.1,0.2,2.2,2.4,2.3,4.55,5.8,0.001])>>>y=np.array(["a","b","b","b","c","c","c","a"])>>>groups=np.array([1,1,2,2,3,3,4,4])>>>train_indx,test_indx=next(...GroupShuffleSplit(random_state=7).split(X,y,groups)...)>>>X_train,X_test,y_train,y_test= \...X[train_indx],X[test_indx],y[train_indx],y[test_indx]>>>X_train.shape,X_test.shape((6,), (2,))>>>np.unique(groups[train_indx]),np.unique(groups[test_indx])(array([1, 2, 4]), array([3]))

3.1.2.6.Cross validation of time series data#

Time series data is characterized by the correlation between observationsthat are near in time (autocorrelation). However, classicalcross-validation techniques such asKFold andShuffleSplit assume the samples are independent andidentically distributed, and would result in unreasonable correlationbetween training and testing instances (yielding poor estimates ofgeneralization error) on time series data. Therefore, it is very importantto evaluate our model for time series data on the “future” observationsleast like those that are used to train the model. To achieve this, onesolution is provided byTimeSeriesSplit.

3.1.2.6.1.Time Series Split#

TimeSeriesSplit is a variation ofk-fold whichreturns first\(k\) folds as train set and the\((k+1)\) thfold as test set. Note that unlike standard cross-validation methods,successive training sets are supersets of those that come before them.Also, it adds all surplus data to the first training partition, whichis always used to train the model.

This class can be used to cross-validate time series data samplesthat are observed at fixed time intervals. Indeed, the folds mustrepresent the same duration, in order to have comparable metrics across folds.

Example of 3-split time series cross-validation on a dataset with 6 samples:

>>>fromsklearn.model_selectionimportTimeSeriesSplit>>>X=np.array([[1,2],[3,4],[1,2],[3,4],[1,2],[3,4]])>>>y=np.array([1,2,3,4,5,6])>>>tscv=TimeSeriesSplit(n_splits=3)>>>print(tscv)TimeSeriesSplit(gap=0, max_train_size=None, n_splits=3, test_size=None)>>>fortrain,testintscv.split(X):...print("%s%s"%(train,test))[0 1 2] [3][0 1 2 3] [4][0 1 2 3 4] [5]

Here is a visualization of the cross-validation behavior.

../_images/sphx_glr_plot_cv_indices_013.png

3.1.3.A note on shuffling#

If the data ordering is not arbitrary (e.g. samples with the same class labelare contiguous), shuffling it first may be essential to get a meaningfulcross-validation result. However, the opposite may be true if the samples are notindependently and identically distributed. For example, if samples correspondto news articles, and are ordered by their time of publication, then shufflingthe data will likely lead to a model that is overfit and an inflated validationscore: it will be tested on samples that are artificially similar (close intime) to training samples.

Some cross validation iterators, such asKFold, have an inbuilt optionto shuffle the data indices before splitting them. Note that:

  • This consumes less memory than shuffling the data directly.

  • By default no shuffling occurs, including for the (stratified) K foldcross-validation performed by specifyingcv=some_integer tocross_val_score, grid search, etc. Keep in mind thattrain_test_split still returns a random split.

  • Therandom_state parameter defaults toNone, meaning that theshuffling will be different every timeKFold(...,shuffle=True) isiterated. However,GridSearchCV will use the same shuffling for each setof parameters validated by a single call to itsfit method.

  • To get identical results for each split, setrandom_state to an integer.

For more details on how to control the randomness of cv splitters and avoidcommon pitfalls, seeControlling randomness.

3.1.4.Cross validation and model selection#

Cross validation iterators can also be used to directly perform modelselection using Grid Search for the optimal hyperparameters of themodel. This is the topic of the next section:Tuning the hyper-parameters of an estimator.

3.1.5.Permutation test score#

permutation_test_score offers another wayto evaluate the performance of apredictor. It provides apermutation-based p-value, which represents how likely an observed performance of theestimator would be obtained by chance. The null hypothesis in this test isthat the estimator fails to leverage any statistical dependency between thefeatures and the targets to make correct predictions on left-out data.permutation_test_score generates a nulldistribution by calculatingn_permutations different permutations of thedata. In each permutation the target values are randomly shuffled, thereby removingany dependency between the features and the targets. The p-value output is the fractionof permutations whose cross-validation score is better or equal than the true scorewithout permuting targets. For reliable resultsn_permutations should typically belarger than 100 andcv between 3-10 folds.

A low p-value provides evidence that the dataset contains some real dependency betweenfeatures and targetsand that the estimator was able to utilize this dependency toobtain good results. A high p-value, in reverse, could be due to either one of these:

  • a lack of dependency between features and targets (i.e., there is no systematicrelationship and any observed patterns are likely due to random chance)

  • or because the estimator was not able to use the dependency in the data (forinstance because it underfit).

In the latter case, using a more appropriate estimator that is able to use thestructure in the data, would result in a lower p-value.

Cross-validation provides information about how well an estimator generalizesby estimating the range of its expected scores. However, anestimator trained on a high dimensional dataset with no structure may stillperform better than expected on cross-validation, just by chance.This can typically happen with small datasets with less than a few hundredsamples.permutation_test_score provides informationon whether the estimator has found a real dependency between features and targets andcan help in evaluating the performance of the estimator.

It is important to note that this test has been shown to produce lowp-values even if there is only weak structure in the data because in thecorresponding permutated datasets there is absolutely no structure. Thistest is therefore only able to show whether the model reliably outperformsrandom guessing.

Finally,permutation_test_score is computedusing brute force and internally fits(n_permutations+1)*n_cv models.It is therefore only tractable with small datasets for which fitting anindividual model is very fast. Using then_jobs parameter parallelizes thecomputation and thus speeds it up.

Examples

References#
On this page

This Page