main content

partition data for cross-凯发k8网页登录

partition data for cross-validation

description

cvpartition defines a random partition on a data set. use this partition to define training and test sets for validating a statistical model using cross-validation. use training to extract the training indices and test to extract the test indices for cross-validation. use repartition to define a new random partition of the same type as a given cvpartition object.

creation

description

c = cvpartition(n,'kfold',k) returns a cvpartition object c that defines a random nonstratified partition for k-fold cross-validation on n observations. the partition randomly divides the observations into k disjoint subsamples, or folds, each of which has approximately the same number of observations.

example

c = cvpartition(n,'holdout',p) creates a random nonstratified partition for holdout validation on n observations. this partition divides the observations into a training set and a test, or holdout, set.

example

c = cvpartition(group,'kfold',k) creates a random partition for stratified k-fold cross-validation. each subsample, or fold, has approximately the same number of observations and contains approximately the same class proportions as in group.

when you specify group as the first input argument, cvpartition discards rows of observations corresponding to missing values in group.

example

c = cvpartition(group,'kfold',k,'stratify',stratifyoption) returns a cvpartition object c that defines a random partition for k-fold cross-validation. if you specify 'stratify',false, then cvpartition ignores the class information in group and creates a nonstratified random partition. otherwise, the function implements stratification by default.

c = cvpartition(group,'holdout',p) randomly partitions observations into a training set and a test, or holdout, set with stratification, using the class information in group. both the training and test sets have approximately the same class proportions as in group.

example

c = cvpartition(group,'holdout',p,'stratify',stratifyoption) returns an object c that defines a random partition into a training set and a test, or holdout, set. if you specify 'stratify',false, then cvpartition creates a nonstratified random partition. otherwise, the function implements stratification by default.

example

c = cvpartition(n,'leaveout') creates a random partition for leave-one-out cross-validation on n observations. leave-one-out is a special case of 'kfold' in which the number of folds equals the number of observations.

c = cvpartition(n,'resubstitution') creates an object c that does not partition the data. both the training set and the test set contain all of the original n observations.

input arguments

number of observations in the sample data, specified as a positive integer scalar.

example: 100

data types: single | double

number of folds in the partition, specified as a positive integer scalar. k must be smaller than the total number of observations.

example: 5

data types: single | double

fraction or number of observations in the test set used for holdout validation, specified as a scalar in the range (0,1) or an integer scalar in the range [1,n), where n is the total number of observations.

  • if p is a scalar in the range (0,1), then cvpartition randomly selects approximately p*n observations for the test set.

  • if p is an integer scalar in the range [1,n), then cvpartition randomly selects p observations for the test set.

example: 0.2

example: 50

data types: single | double

grouping variable for stratification, specified as a numeric or logical vector, a categorical, character, or string array, or a cell array of character vectors indicating the class of each observation. cvpartition creates a partition from the observations in group.

data types: single | double | logical | categorical | char | string | cell

indicator for stratification, specified as true or false.

  • if the first input argument to cvpartition is group, then cvpartition implements stratification by default ('stratify',true). for a nonstratified random partition, specify 'stratify',false.

  • if the first input argument to cvpartition is n, then cvpartition always creates a nonstratified random partition ('stratify',false). in this case, you cannot specify 'stratify',true.

data types: logical

properties

this property is read-only.

number of observations, including observations with missing group values, specified as a positive integer scalar.

data types: double

this property is read-only.

total number of test sets in the partition, specified as the number of folds when the partition type is 'kfold' or 'leaveout', and 1 when the partition type is 'holdout' or 'resubstitution'.

data types: double

this property is read-only.

size of each test set, specified as a positive integer vector when the partition type is 'kfold' or 'leaveout', and a positive integer scalar when the partition type is 'holdout' or 'resubstitution'.

data types: double

this property is read-only.

size of each training set, specified as a positive integer vector when the partition type is 'kfold' or 'leaveout', and a positive integer scalar when the partition type is 'holdout' or 'resubstitution'.

data types: double

this property is read-only.

type of validation partition, specified as 'kfold', 'holdout', 'leaveout', or 'resubstitution'.

object functions

repartition data for cross-validation
test indices for cross-validation
training indices for cross-validation

examples

use the cross-validation misclassification error to estimate how a model will perform on new data.

load the ionosphere data set. create a table containing the predictor data x and the response variable y.

load ionosphere
tbl = array2table(x);
tbl.y = y;

use a random nonstratified partition hpartition to split the data into training data (tbltrain) and a reserved data set (tblnew). reserve approximately 30 percent of the data.

rng('default') % for reproducibility
n = length(tbl.y);
hpartition = cvpartition(n,'holdout',0.3); % nonstratified partition
idxtrain = training(hpartition);
tbltrain = tbl(idxtrain,:);
idxnew = test(hpartition);
tblnew = tbl(idxnew,:);

train a support vector machine (svm) classification model using the training data tbltrain. calculate the misclassification error and the classification accuracy on the training data.

mdl = fitcsvm(tbltrain,'y');
trainerror = resubloss(mdl)
trainerror = 0.0569
trainaccuracy = 1-trainerror
trainaccuracy = 0.9431

typically, the misclassification error on the training data is not a good estimate of how a model will perform on new data because it can underestimate the misclassification rate on new data. a better estimate is the cross-validation error.

create a partitioned model cvmdl. compute the 10-fold cross-validation misclassification error and classification accuracy. by default, crossval ensures that the class proportions in each fold remain approximately the same as the class proportions in the response variable tbltrain.y.

cvmdl = crossval(mdl); % performs stratified 10-fold cross-validation
cvtrainerror = kfoldloss(cvmdl)
cvtrainerror = 0.1220
cvtrainaccuracy = 1-cvtrainerror
cvtrainaccuracy = 0.8780

notice that the cross-validation error cvtrainerror is greater than the resubstitution error trainerror.

classify the new data in tblnew using the trained svm model. compare the classification accuracy on the new data to the accuracy estimates trainaccuracy and cvtrainaccuracy.

newerror = loss(mdl,tblnew,'y');
newaccuracy = 1-newerror
newaccuracy = 0.8700

the cross-validation error gives a better estimate of the model performance on new data than the resubstitution error.

use the same stratified partition for 5-fold cross-validation to compute the misclassification rates of two models.

load the fisheriris data set. the matrix meas contains flower measurements for 150 different flowers. the variable species lists the species for each flower.

load fisheriris

create a random partition for stratified 5-fold cross-validation. the training and test sets have approximately the same proportions of flower species as species.

rng('default') % for reproducibility
c = cvpartition(species,'kfold',5);

create a partitioned discriminant analysis model and a partitioned classification tree model by using c.

discrcvmodel = fitcdiscr(meas,species,'cvpartition',c);
treecvmodel = fitctree(meas,species,'cvpartition',c);

compute the misclassification rates of the two partitioned models.

discrrate = kfoldloss(discrcvmodel)
discrrate = 0.0200
treerate = kfoldloss(treecvmodel)
treerate = 0.0333

the discriminant analysis model has a smaller cross-validation misclassification rate.

observe the test set (fold) class proportions in a 5-fold nonstratified partition of the fisheriris data. the class proportions differ across the folds.

load the fisheriris data set. the species variable contains the species name (class) for each flower (observation). convert species to a categorical variable.

load fisheriris
species = categorical(species);

find the number of observations in each class. notice that the three classes occur in equal proportion.

c = categories(species) % class names
c = 3x1 cell
    {'setosa'    }
    {'versicolor'}
    {'virginica' }
numclasses = size(c,1);
n = countcats(species) % number of observations in each class
n = 3×1
    50
    50
    50

create a random nonstratified 5-fold partition.

rng('default') % for reproducibility
cv = cvpartition(species,'kfold',5,'stratify',false) 
cv = 
k-fold cross validation partition
   numobservations: 150
       numtestsets: 5
         trainsize: 120  120  120  120  120
          testsize: 30  30  30  30  30

show that the three classes do not occur in equal proportion in each of the five test sets, or folds. use a for-loop to update the ntestdata matrix so that each entry ntestdata(i,j) corresponds to the number of observations in test set i and class c(j). create a bar chart from the data in ntestdata.

numfolds = cv.numtestsets;
ntestdata = zeros(numfolds,numclasses);
for i = 1:numfolds
    testclasses = species(cv.test(i));
    ncounts = countcats(testclasses); % number of test set observations in each class
    ntestdata(i,:) = ncounts';
end
bar(ntestdata)
xlabel('test set (fold)')
ylabel('number of observations')
title('nonstratified partition')
legend(c)

figure contains an axes object. the axes object with title nonstratified partition, xlabel test set (fold), ylabel number of observations contains 3 objects of type bar. these objects represent setosa, versicolor, virginica.

notice that the class proportions vary in some of the test sets. for example, the first test set contains 8 setosa, 13 versicolor, and 9 virginica flowers, rather than 10 flowers per species. because cv is a random nonstratified partition of the fisheriris data, the class proportions in each test set (fold) are not guaranteed to be equal to the class proportions in species. that is, the classes do not always occur equally in each test set, as they do in species.

create a nonstratified holdout partition and a stratified holdout partition for a tall array. for the two holdout sets, compare the number of observations in each class.

when you perform calculations on tall arrays, matlab® uses either a parallel pool (the default if you have parallel computing toolbox™) or the local matlab session. to run the example using the local matlab session when you have parallel computing toolbox, change the global execution environment by using the function.

mapreducer(0)

create a numeric vector of two classes, where class 1 and class 2 occur in the ratio 1:10.

group = [ones(20,1);2*ones(200,1)]
group = 220×1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
      ⋮

create a tall array from group.

tgroup = tall(group)
tgroup =
  220x1 tall double column vector
     1
     1
     1
     1
     1
     1
     1
     1
     :
     :

holdout is the only cvpartition option that is supported for tall arrays. create a random nonstratified holdout partition.

cv0 = cvpartition(tgroup,'holdout',1/4,'stratify',false)  
cv0 = 
hold-out cross validation partition
   numobservations: [1x1 tall]
       numtestsets: 1
         trainsize: [1x1 tall]
          testsize: [1x1 tall]

return the result of cv0.test to memory by using the gather function.

testidx0 = gather(cv0.test);
evaluating tall expression using the local matlab session:
- pass 1 of 1: completed in 0.27 sec
evaluation completed in 0.39 sec

find the number of times each class occurs in the test, or holdout, set.

accumarray(group(testidx0),1) % number of observations per class in the holdout set
ans = 2×1
     5
    51

cvpartition produces randomness in the results, so your number of observations in each class can vary from those shown.

because cv0 is a nonstratified partition, class 1 observations and class 2 observations in the holdout set are not guaranteed to occur in the same ratio as in tgroup. however, because of the inherent randomness in cvpartition, you can sometimes obtain a holdout set in which the classes occur in the same ratio as in tgroup, even though you specify 'stratify',false. because the training set is the complement of the holdout set, excluding any nan or missing observations, you can obtain a similar result for the training set.

return the result of cv0.training to memory.

trainidx0 = gather(cv0.training);
evaluating tall expression using the local matlab session:
- pass 1 of 1: completed in 0.1 sec
evaluation completed in 0.14 sec

find the number of times each class occurs in the training set.

accumarray(group(trainidx0),1) % number of observations per class in the training set
ans = 2×1
    15
   149

the classes in the nonstratified training set are not guaranteed to occur in the same ratio as in tgroup.

create a random stratified holdout partition.

cv1 = cvpartition(tgroup,'holdout',1/4)  
cv1 = 
hold-out cross validation partition
   numobservations: [1x1 tall]
       numtestsets: 1
         trainsize: [1x1 tall]
          testsize: [1x1 tall]

return the result of cv1.test to memory.

testidx1 = gather(cv1.test);
evaluating tall expression using the local matlab session:
- pass 1 of 1: completed in 0.064 sec
evaluation completed in 0.084 sec

find the number of times each class occurs in the test, or holdout, set.

accumarray(group(testidx1),1) % number of observations per class in the holdout set
ans = 2×1
     5
    51

in the case of the stratified holdout partition, the class ratio in the holdout set and the class ratio in tgroup are the same (1:10).

create a random partition of data for leave-one-out cross-validation. compute and compare training set means. a repetition with a significantly different mean suggests the presence of an influential observation.

create a data set x that contains one value that is much greater than the others.

x = [1 2 3 4 5 6 7 8 9 20]';

create a cvpartition object that has 10 observations and 10 repetitions of training and test data. for each repetition, cvpartition selects one observation to remove from the training set and reserve for the test set.

c = cvpartition(10,'leaveout')
c = 
leave-one-out cross validation partition
   numobservations: 10
       numtestsets: 10
         trainsize: 9  9  9  9  9  9  9  9  9  9
          testsize: 1  1  1  1  1  1  1  1  1  1

apply the leave-one-out partition to x, and take the mean of the training observations for each repetition by using crossval.

values = crossval(@(xtrain,xtest)mean(xtrain),x,'partition',c)
values = 10×1
    6.5556
    6.4444
    7.0000
    6.3333
    6.6667
    7.1111
    6.8889
    6.7778
    6.2222
    5.0000

view the distribution of the training set means using a box chart (or box plot). the plot displays one outlier.

boxchart(values)

figure contains an axes object. the axes object contains an object of type boxchart.

find the repetition corresponding to the outlier value. for that repetition, find the observation in the test set.

[~,repetitionidx] = min(values)
repetitionidx = 10
observationidx = test(c,repetitionidx);
influentialobservation = x(observationidx)
influentialobservation = 20

training sets that contain the observation have substantially different means from the mean of the training set without the observation. this significant change in mean suggests that the value of 20 in x is an influential observation.

tips

  • if you specify group as the first input argument to cvpartition, then the function discards rows of observations corresponding to missing values in group.

  • if you specify group as the first input argument to cvpartition, then the function implements stratification by default. you can specify 'stratify',false to create a nonstratified random partition.

  • you can specify 'stratify',true only when the first input argument to cvpartition is group.

extended capabilities

version history

introduced in r2008a

see also

| | |

topics

    网站地图