%% Assemble Network from Pretrained Keras Layers
% This example shows how to import the layers from a pretrained Keras network, replace the unsupported layers with custom layers, and assemble the layers into a network ready for prediction.
%
%% Import Keras Network
% Import the layers from a Keras network model. The network in 'digitsDAGnetwithnoise.h5' classifies images of digits.

filename = 'digitsDAGnetwithnoise.h5';
lgraph = importKerasLayers(filename,'ImportWeights',true);

% The Keras network contains some layers that are not supported by Deep Learning Toolbox. The importKerasLayers function displays a warning and replaces the unsupported layers with placeholder layers.
% Plot the layer graph using plot.

figure
plot(lgraph)
title("Imported Network")

%
%% Replace Placeholder Layers
% To replace the placeholder layers, first identify the names of the layers to replace. Find the placeholder layers using findPlaceholderLayers.

placeholderLayers = findPlaceholderLayers(lgraph)

% Display the Keras configurations of these layers.

placeholderLayers.KerasConfiguration

% Define a custom Gaussian noise layer. To create this layer, save the file gaussianNoiseLayer.m in the current folder. Then, create two Gaussian noise layers with the same configurations as the imported Keras layers.

gnLayer1 = gaussianNoiseLayer(1.5,'new_gaussian_noise_1');
gnLayer2 = gaussianNoiseLayer(0.7,'new_gaussian_noise_2');

% Replace the placeholder layers with the custom layers using replaceLayer.

lgraph = replaceLayer(lgraph,'gaussian_noise_1',gnLayer1);
lgraph = replaceLayer(lgraph,'gaussian_noise_2',gnLayer2);

% Plot the updated layer graph using plot.

figure
plot(lgraph)
title("Network with Replaced Layers")

%
%% Specify Class Names
% If the imported classification layer does not contain the classes, then you must specify these before prediction. If you do not specify the classes, then the software automatically sets the classes to 1, 2, ..., N, where N is the number of classes.
% Find the index of the classification layer by viewing the Layers property of the layer graph.

lgraph.Layers

% The classification layer has the name 'ClassificationLayer_activation_1'. View the classification layer and check the Classes property.

cLayer = lgraph.Layers(end)

% Because the Classes property of the layer is 'auto', you must specify the classes manually. Set the classes to 0, 1, ..., 9, and then replace the imported classification layer with the new one.

cLayer.Classes = string(0:9)
lgraph = replaceLayer(lgraph,'ClassificationLayer_activation_1',cLayer);

%
%% Assemble Network
% Assemble the layer graph using assembleNetwork. The function returns a DAGNetwork object that is ready to use for prediction.

net = assembleNetwork(lgraph)

% Copyright 2018 The MathWorks, Inc.