rootFolder = fullfile('c:\', 'Users', 'Ws Liew', 'Documents', 'MATLAB', 'Dataset');
categories = {'normal', 'abnormal'};
imds = imageDatastore(fullfile(rootFolder, categories), 'LabelSource','foldernames');
countEachLabel(imds)
normal = find(imds.Labels == 'normal', 1);
abnormal = find(imds.Labels == 'abnormal', 1);
net = alexnet;
featureLayer = 'fc8';
net.Layers
net.Layers(1)
net.Layers(end)
numel(net.Layers(end).ClassNames)
[trainingSet, testSet] = splitEachLabel(imds, 0.65, 'randomized');
imageSize = net.Layers(1).InputSize;
augmentedTrainingSet = augmentedImageDatastore(imageSize(1:2), trainingSet, 'ColorPreprocessing', 'gray2rgb');
augmentedTestSet = augmentedImageDatastore(imageSize(1:2), testSet, 'ColorPreprocessing', 'gray2rgb');
w1 = net.Layers(2).Weights;
w1 = mat2gray(w1);
w1 = imresize(w1,5);
trainingFeatures = activations(net, augmentedTrainingSet, featureLayer, 'OutputAs', 'rows');
trainingFeatures = double(trainingFeatures);
testFeatures = activations(net, augmentedTestSet, featureLayer, 'OutputAs', 'rows');
testFeatures = double(testFeatures);
trainingLabels = trainingSet.Labels;
trainingLabels = cellstr(trainingLabels);
testLabels = testSet.Labels;
testLabels = cellstr(testLabels);
rng(1);
t = templateSVM('Standardize',1)
Md1 = fitcecoc(double(trainingFeatures), cellstr(trainingLabels),'Learners',t, 'FitPosterior',1, 'ClassNames',{'normal','abnormal'});
CVMdl = crossval(Md1);
loss = kfoldLoss(CVMdl)
predictedLabels = predict(Md1, testFeatures);
[predictedLabels,~,~,Posterior] = predict(Md1,testFeatures);
[X,Y,T,AUC,OPTROCPT,SUBY,SUBYNAMES] = perfcurve(testLabels, Posterior(:,2), 'abnormal');
figure(1)
plot(X,Y);
xlabel('False positive rate')
ylabel('True positive rate')
title('ROC for Classification CNN')
AUC