Import a pretrained TensorFlow network in the saved model format as a DAGNetwork object, and use the imported network to classify an image. The imported network contains layers that are not supported for conversion into built-in MATLAB layers. The software automatically generates custom layers when you import these layers.
This example uses the helper function findCustomLayers. To view the code for this function, see Helper Function.
Specify the model folder.
if ~exist('digitsDAGnetwithnoise','dir')
unzip('digitsDAGnetwithnoise.zip')
end
modelFolder = './digitsDAGnetwithnoise';
Specify the class names.
classNames = {'0','1','2','3','4','5','6','7','8','9'};
Import a TensorFlow network in the saved model format. By default, importTensorFlowNetwork imports the network as a DAGNetwork object. Specify the output layer type for an image classification problem.
net = importTensorFlowNetwork(modelFolder,'OutputLayerType','classification','Classes',classNames);
Importing the saved model...
Translating the model, this may take a few minutes...
Finished translation. Assembling network...
Import finished.
If the imported network contains layers not supported for conversion into built-in MATLAB layers, then importTensorFlowNetwork can automatically generate custom layers in place of these layers. importTensorFlowNetwork saves each generated custom layer to a separate .m file in the package +digitsDAGnetwithnoise in the current folder.
Find the indices of the automatically generated custom layers using the helper function findCustomLayers, and display the custom layers.
ind = findCustomLayers(net.Layers,'+digitsDAGnetwithnoise');
net.Layers(ind)
ans =
2×1 Layer array with layers:
1 'gaussian_noise_1' GaussianNoise digitsDAGnetwithnoise.kGaussianNoise1Layer3766
2 'gaussian_noise_2' GaussianNoise digitsDAGnetwithnoise.kGaussianNoise2Layer3791
Plot the network architecture.
plot(net)
title('DAG Network Architecture')
Read the image you want to classify.
digitDatasetPath = fullfile(toolboxdir('nnet'),'nndemos','nndatasets','DigitDataset');
I = imread(fullfile(digitDatasetPath,'5','image4009.png'));
Classify the image using the pretrained network.
label = classify(net,I);
Display the image and the classification result.
imshow(I)
title(['Classification result ' char(label)])
Helper Function
This section provides the code of the helper function findCustomLayers used in this example. findCustomLayers returns the indices of the custom layers that importTensorFlowNetwork automatically generates.
function indices = findCustomLayers(layers,PackageName)
s = what(['.\' PackageName]);
indices = zeros(1,length(s.m));
for i = 1:length(layers)
for j = 1:length(s.m)
if strcmpi(class(layers(i)),[PackageName(2:end) '.' s.m{j}(1:end-2)])
indices(j) = i;
end
end
end
end