% kfoldloss_demo.m
% Explain the use of the function using Naive Bayes Classifier
% Dr. W.D. Pan, UAH

clear all;
close all;

K = 10      % K-fold cross validation
load fisheriris


rng(1);     % For reproducibility
cv = cvpartition(species,'KFold', 5)
Model_cv = fitcnb(meas, species, 'CVPartition', cv);
% Equivalently
% Model_cv = fitcnb(meas, species,'CrossVal','on','KFold',K);

Model_cv;
Model_cv.Partition;

error_rate_1 = kfoldLoss(Model_cv,'LossFun','ClassifErr')

% Alternatively, use cvpartition function
rng(1);     % For reproducibility
cv_part = cvpartition(species,'KFold',K);

Errors = zeros(1, K);

for i = 1: K
    training_index = cv_part.training(i);
    testing_index = cv_part.test(i);
    
    Model = fitcnb(meas(training_index,:), species(training_index,:));
    % Then predict using the testing data
    label = predict(Model, meas(testing_index,:));
    diff = strcmp (label, species(testing_index,:));
    Errors(i) = length(find(diff==0))/length(label);
end

error_rate_2 = mean(Errors)





