How can I use 5fold cross validation on my dataset?

2 views (last 30 days)
I have a 24099x40 matrix consisting of daily asset returns in which I want to do a 5fold cross validation. How can I go about doing this? I have tried to figure out how crossval and other similar functions work, but I still do not quite understand it. I have also seen that it is possible to use a for loop.
Thank you!

Answers (1)

Anant Upadhyay
Anant Upadhyay on 8 Mar 2019
Hi Jakob,
Please refer to the following code for using 5fold cross validation on dataset.
load('fisheriris');
% load fisher iris dataset
% It will load “meas” a 150x4 matrix of observation, and “species” their corresponding class.
% cvparitition is used to create a k fold cross-validation partition of dataset.
CVO = cvpartition(species,'k',5);
err = zeros(CVO.NumTestSets,1);
for i = 1:CVO.NumTestSets
% CVO.training returns a logical(1 or 0) array of size same as species with indices marked as 1 for training.
trIdx = CVO.training(i);
teIdx = CVO.test(i);
% Classifying on the test set
ytest = classify(meas(teIdx,:),meas(trIdx,:), species(trIdx,:));
err(i) = sum(~strcmp(ytest,species(teIdx)));
end
% cvErr will have the mean cross-validation err
cvErr = sum(err)/sum(CVO.TestSize);
You can check the following documentation for 'cvpartition':

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!