MATLAB: How to display confusion matrix for each fold

classificationconfusion matrixmachinelearningnaive bayes

Hi guys, i'm using 10 times k fold cross validation for the implementation of machine learning.. i would like to display the confusion matrix for each fold..
Here's the example of my code..
function NB=jNB(feat,label,Dist,kfold)
switch Dist
case'n'; Dist='normal';
case'k'; Dist='kernel';
end
rng('default');
% Divide data into k-folds
fold=cvpartition(label,'kfold',kfold);
% Pre
pred2=[]; ytest2=[]; Afold=zeros(kfold,1);
% Naive Bayes start
for i=1:kfold
% Call index of training & testing sets
trainIdx=fold.training(i); testIdx=fold.test(i);
% Call training & testing features and labels
xtrain=feat(trainIdx,:); ytrain=label(trainIdx);
xtest=feat(testIdx,:); ytest=label(testIdx);
% Training the model
Model=fitcnb(xtrain,ytrain,'Distribution',Dist);
% Perform testing
Pred0=predict(Model,xtest); %A=size(Pred0,1);
% Confusion matrix
con=confusionmat(ytest,Pred0);
% Accuracy for each fold
Afold(i)=100*sum(diag(con))/sum(con(:));
%classperf
D=classperf(ytest,Pred0);
%Sensitivity for each fold
Bfold(i)=100*(D.Sensitivity);
%Specificity for each fold
Cfold(i)=100*(D.Specificity);
% Store temporary
pred2=[pred2(1:end);Pred0]; ytest2=[ytest2(1:end);ytest];
end
with that code i can only display one confusion matrix. what i want is display 10 confusion matrix for each validation. i do really appreciate your help and your answer.. Thank You

Best Answer

Hi Financeo,
If the purpose is only to display the confusion matrix for each validation. The following approaches can be used
1) Add a line below the code that calculates the confusion matrix
con=confusionmat(ytest,Pred0);
disp(['The Confusion matrix for fold number ' num2str(i)])
disp(con)
2) Remove the semicolon at the line calculates the confusion matrix. But this slows down the processs a bit
con=confusionmat(ytest,Pred0)
3) Preallocate the space for confusion matrix
% Suppose the size of confusion matrix is N
% Add the below statement before the for loop
con = zeros(N,N,kfold);
%...

% In the for loop

con(:,:,i) = confusionmat(ytest,Pred0);
% Another possibility
% If you are unsure of the size of matrix, initialize with cell
con = cell(1,N);
%...
% In the for loop
con{i} = confusionmat(ytest,Pred0);
% The confusion matrix will be in a cell array and you can know the output by indexing cond{1} for 1-fold and similarly for other folds too
% in this case, you could even output con as second output argument for the function
Hope this helps.
Regards,
Sriram
Related Question