
ACC=[];
result=[];
AAA=[];
digitDatasetPath = 'Digital path of the dataset';
digitData = imageDatastore(digitDatasetPath, ...
    'IncludeSubfolders',true,'LabelSource','foldernames');
[trainDigitData,testDigitData] = splitEachLabel(digitData,0.7);

% By AlexNet
net=alexnet; %Here the net provided by MATLAB R2021b was pre-trained with ImageNet dataset
inputSize = net.Layers(1).InputSize;
auimdstrain = augmentedImageDatastore(inputSize,trainDigitData,'ColorPreprocessing', 'gray2rgb');
auimdstest = augmentedImageDatastore(inputSize,testDigitData,'ColorPreprocessing', 'gray2rgb');
layersTransfer = net.Layers(1:end-3);
numClasses = numel(categories(trainDigitData.Labels));
layers = [...
    layersTransfer % For the original AlexNet, kindly delete the added layers
    fullyConnectedLayer(10) % For the improved AlexNet, additional layers were added into the net architecture
    fullyConnectedLayer(numClasses,'WeightLearnRateFactor',20,'BiasLearnRateFactor',20)
    softmaxLayer
    classificationLayer];
optionsTransfer = trainingOptions('sgdm',...
    'MaxEpochs',64,...
    'MiniBatchSize', 100,...
    'InitialLearnRate',0.0003,...
    'Plots','training-progress');
netTransfer = trainNetwork(auimdstrain,layers,optionsTransfer);

[YPred,p] = classify(netTransfer,auimdstest);
YTest = testDigitData.Labels;
accuracy = sum(YPred==YTest)/numel(YTest);
ACC=[ACC;accuracy];
result=[result,double(YPred)];

trainingFeatures = activations(netTransfer,auimdstrain,23,'OutputAs','rows');
trainingFeatures1 = activations(netTransfer,auimdstest,23,'OutputAs','rows');
OUT=[trainingFeatures;trainingFeatures1];
AAA=[AAA,OUT];
net2=net;
L=[];
L.Layers=layers;
L.InputNames=net2.InputNames;
L.OutputNames=net2.OutputNames;
testFeatures = activations(netTransfer,auimdstest,23,'OutputAs','rows');
