Visualizing cross-validation behavior in scikit-learn
Choosing the right cross-validation object is a crucial part of fitting a
model properly. There are many ways to split data into training and test
sets in order to avoid model overfitting, to standardize the number of
groups in test sets, etc.
This example visualizes the behavior of several common scikit-learn objects
for comparison.
# Authors: The scikit-learn developers# SPDX-License-Identifier: BSD-3-Clauseimportmatplotlib.pyplotaspltimportnumpyasnpfrommatplotlib.patchesimport
First, we must understand the structure of our data. It has 100 randomly
generated input datapoints, 3 classes split unevenly across datapoints,
and 10 “groups” split evenly across datapoints.
As we’ll see, some cross-validation objects do specific things with
labeled data, others behave differently with grouped data, and others
do not use this information.
Define a function to visualize cross-validation behavior
We’ll define a function that lets us visualize the behavior of each
cross-validation object. We’ll perform 4 splits of the data. On each
split, we’ll visualize the indices chosen for the training set
(in blue) and the test set (in red).
defplot_cv_indices(cv,X,y,group,ax,n_splits,lw=10):"""Create a sample plot for indices of a cross-validation object."""use_groups="Group"intype(cv).__name__groups=groupifuse_groupselseNone# Generate the training/testing visualizations for each CV splitforii,(tr,tt)inenumerate(cv.split(X=X,y=y,groups=groups)):# Fill in indices with the training/test groupsindices=np.array([np.nan]*len(X))indices[tt]=1indices[tr]=0# Visualize the resultsax.scatter(range(len(indices)),[ii+0.5]*len(indices),c=indices,marker="_",lw=lw,cmap=cmap_cv,vmin=-0.2,vmax=1.2,)# Plot the data classes and groups at the endax.scatter(range(len(X)),[ii+1.5]*len(X),c=y,marker="_",lw=lw,cmap=cmap_data)ax.scatter(range(len(X)),[ii+2.5]*len(X),c=group,marker="_",lw=lw,cmap=cmap_data)# Formattingyticklabels=list(range(n_splits))+["class","group"]ax.set(yticks=np.arange(n_splits+2)+0.5,yticklabels=yticklabels,xlabel="Sample index",ylabel="CV iteration",ylim=[n_splits+2.2,-0.2],xlim=[0,100],)ax.set_title("{}".format(type(cv).__name__),fontsize=15)returnax
Let’s see how it looks for the KFold
cross-validation object:
As you can see, by default the KFold cross-validation iterator does not
take either datapoint class or group into consideration. We can change this
by using either:
StratifiedKFold to preserve the percentage of samples for each class.
GroupKFold to ensure that the same group will not appear in two
different folds.
StratifiedGroupKFold to keep the constraint of GroupKFold while
attempting to return stratified folds.
Next we’ll visualize this behavior for a number of CV iterators.
Visualize cross-validation indices for many CV objects
Let’s visually compare the cross validation behavior for many
scikit-learn cross-validation objects. Below we will loop through several
common cross-validation objects, visualizing the behavior of each.
Note how some use the group/class information while others do not.