Image being labelled something else than in database
1 view (last 30 days)
Show older comments
Avinav Kumar
on 21 Mar 2021
Commented: Avinav Kumar
on 21 Mar 2021
I am doing an image classification. Have given my database, but end result is identyfing something else , mentioning also something else in result which is not in database.
imds = imageDatastore('Dynacards', ...
'IncludeSubfolders',true, ...
'LabelSource','foldernames');
[imdsTrain,imdsValidation] = splitEachLabel(imds,0.7,'randomized');
numTrainImages = numel(imdsTrain.Labels);
idx = randperm(numTrainImages,16);
figure;
for i = 1:16
subplot(4,4,i);
I = readimage(imdsTrain,idx(i));
imshow(I);
end
%net = trainNetwork(datastore,layers,options);
%net = alexnet;
%analyzeNetwork(net)
%numel(net.Layers(end).ClassNames)
%net = alexnet;
%analyzeNetwork(net);
inputSize = net.Layers(1).InputSize;
layersTransfer = net.Layers(1:end-3);
numClasses = numel(categories(imdsTrain.Labels));
layers = [
layersTransfer
fullyConnectedLayer(numClasses,'WeightLearnRateFactor',20,'BiasLearnRateFactor',20)
softmaxLayer
classificationLayer];
%Train Network
%The network requires input images of size 227-by-227-by-3, but the images in the image datastores have different sizes. Use an augmented image datastore to automatically resize the training images. Specify additional augmentation operations to perform on the training images: randomly flip the training images along the vertical axis, and randomly translate them up to 30 pixels horizontally and vertically. Data augmentation helps prevent the network from overfitting and memorizing the exact details of the training images.
pixelRange = [-30 30];
imageAugmenter = imageDataAugmenter( ...
'RandXReflection',true, ...
'RandXTranslation',pixelRange, ...
'RandYTranslation',pixelRange);
augimdsTrain = augmentedImageDatastore(inputSize(1:2),imdsTrain, ...
'DataAugmentation',imageAugmenter);
%To automatically resize the validation images without performing further data augmentation, use an augmented image datastore without specifying any additional preprocessing operations.
augimdsValidation = augmentedImageDatastore(inputSize(1:2),imdsValidation);
%Specify the training options. For transfer learning, keep the features from the early layers of the pretrained network (the transferred layer weights). To slow down learning in the transferred layers, set the initial learning rate to a small value. In the previous step, you increased the learning rate factors for the fully connected layer to speed up learning in the new final layers. This combination of learning rate settings results in fast learning only in the new layers and slower learning in the other layers. When performing transfer learning, you do not need to train for as many epochs. An epoch is a full training cycle on the entire training data set. Specify the mini-batch size and validation data. The software validates the network every ValidationFrequency iterations during training.
options = trainingOptions('sgdm', ...
'MiniBatchSize',10, ...
'MaxEpochs',6, ...
'InitialLearnRate',1e-4, ...
'Shuffle','every-epoch', ...
'ValidationData',augimdsValidation, ...
'ValidationFrequency',3, ...
'Verbose',false, ...
'Plots','training-progress');
%Train the network that consists of the transferred and new layers. By default, trainNetwork uses a GPU if one is available (requires Parallel Computing Toolbox™ and a CUDA® enabled GPU with compute capability 3.0 or higher). Otherwise, it uses a CPU. You can also specify the execution environment by using the 'ExecutionEnvironment' name-value pair argument of trainingOptions.
netTransfer = trainNetwork(augimdsTrain,layers,options);
%Classify Validation Images
%Classify the validation images using the fine-tuned network.
[YPred,scores] = classify(netTransfer,augimdsValidation);
%YPred = classify(netTransfer,augimdsValidation);
%YPred = classify(net,imdsTest_rsz);
%Display four sample validation images with their predicted labels.
idx = randperm(numel(imdsValidation.Files),4);
figure
for i = 1:4
subplot(2,2,i)
I = readimage(imdsValidation,idx(i));
imshow(I)
label = YPred(idx(i));
title(string(label));
end
%Calculate the classification accuracy on the validation set. Accuracy is the fraction of labels that the network predicts correctly.
%YValidation = imdsValidation.Labels;
%accuracy = mean(YPred == YValidation);
save net
I = imread("14.jpg");
I = imresize(I, [227 227]);
[YPred,probs] = classify(net,I);
imshow(I)
label = YPred;
title(string(label) + ", " + num2str(100*max(probs),3) + "%");
%I = imread("12.jpg");
%I = imresize(I, [227 227]);
%[YPred,probs] = classify(net,I);
%scores = max(double(scores*100));
%imshow(I);
%title(join([string(Pred),'' ,scores ,'%']))
3 Comments
Walter Roberson
on 21 Mar 2021
And the other ones get ranted at or have the word deleted as soon as I have time to clean them up, which I actively do.
Accepted Answer
Joss Knight
on 21 Mar 2021
Edited: Joss Knight
on 21 Mar 2021
You have called classify using the variable net. But the network you trained is called netTransfer.
%Train the network that consists of the transferred and new layers. By default, trainNetwork uses a GPU if one is available (requires Parallel Computing Toolbox™ and a CUDA® enabled GPU with compute capability 3.0 or higher). Otherwise, it uses a CPU. You can also specify the execution environment by using the 'ExecutionEnvironment' name-value pair argument of trainingOptions.
netTransfer = trainNetwork(augimdsTrain,layers,options);
...
%Calculate the classification accuracy on the validation set. Accuracy is the fraction of labels that the network predicts correctly.
%YValidation = imdsValidation.Labels;
%accuracy = mean(YPred == YValidation);
save net
I = imread("14.jpg");
I = imresize(I, [227 227]);
[YPred,probs] = classify(net,I);
...
More Answers (0)
See Also
Categories
Find more on Image Data Workflows in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!