How to load my pre trained model and use it to predict an image

4 views (last 30 days)
I have my saved model. I want to load it on another script. I want to know how to load and clasiffy whether the detected image is correct or not?
tic
imds = imageDatastore('C:\Users\Renit\Desktop\lab1', ...
'IncludeSubfolders',true, ...
'LabelSource','foldernames');
imds.ReadFcn = @(filename)readAndPreprocessImage(filename);
[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
time=toc
tic
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];
pixelRange = [-30 30];
imageAugmenter = imageDataAugmenter( ...
'RandXReflection',true, ...
'RandXTranslation',pixelRange, ...
'RandYTranslation',pixelRange);
augimdsTrain = augmentedImageDatastore(inputSize(1:2),imdsTrain, ...
'DataAugmentation',imageAugmenter);
augimdsValidation = augmentedImageDatastore(inputSize(1:2),imdsValidation);
options = trainingOptions('sgdm', ...
'MiniBatchSize',32, ...
'MaxEpochs',10, ...
'InitialLearnRate',1e-4, ...
'Shuffle','every-epoch', ...
'ValidationData',augimdsValidation, ...
'ValidationFrequency',3, ...
'Verbose',false, ...
'Plots','training-progress');
netTransfer = trainNetwork(augimdsTrain,layers,options);
gregnet1 = netTransfer;
save gregnet1
[YPred,scores] = classify(netTransfer,augimdsValidation);
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
YValidation = imdsValidation.Labels;
accuracy = mean(YPred == YValidation)
I want the line after "save gregnet1" to be another script and i need to load the gregnet to just clasiffy whether the image is correctly detected or not.

Answers (1)

Mohammad Sami
Mohammad Sami on 30 Aug 2020
The variable gregnet can be saved and loaded from a .mat file like any other variables.
save('mynet.mat','gregnet1'); file = load('mynet.mat'); gregnet1 = file.gregnet1;
  1 Comment
renit anthony
renit anthony on 30 Aug 2020
Yeah got it. My gregnet1.mat has been saved. Can you give me an example wherein I can load this model and used it to classify an image. ?

Sign in to comment.

Categories

Find more on Deep Learning Toolbox 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!