exponenta event banner

Сборка сети из предварительно обученных слоев Keras

В этом примере показано, как импортировать слои из предварительно подготовленной сети Keras, заменить неподдерживаемые слои пользовательскими и собрать слои в сеть, готовую для прогнозирования.

Импорт сети Keras

Импортируйте слои из сетевой модели Keras. Сеть в 'digitsDAGnetwithnoise.h5' классифицирует изображения цифр.

filename = 'digitsDAGnetwithnoise.h5';
lgraph = importKerasLayers(filename,'ImportWeights',true);
Warning: Unable to import some Keras layers, because they are not supported by the Deep Learning Toolbox. They have been replaced by placeholder layers. To find these layers, call the function findPlaceholderLayers on the returned object.

Сеть Keras содержит некоторые слои, которые не поддерживаются Deep Learning Toolbox. importKerasLayers функция отображает предупреждение и заменяет неподдерживаемые слои слоями-местозаполнителями.

Печать графика слоев с помощью plot.

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

Figure contains an axes. The axes with title Imported Network contains an object of type graphplot.

Заменить слои-заполнители

Чтобы заменить слои-заполнители, сначала определите имена слоев для замены. Поиск слоев-заполнителей с помощью findPlaceholderLayers.

placeholderLayers = findPlaceholderLayers(lgraph)
placeholderLayers = 
  2x1 PlaceholderLayer array with layers:

     1   'gaussian_noise_1'   PLACEHOLDER LAYER   Placeholder for 'GaussianNoise' Keras layer
     2   'gaussian_noise_2'   PLACEHOLDER LAYER   Placeholder for 'GaussianNoise' Keras layer

Отображение конфигураций Keras этих слоев.

placeholderLayers.KerasConfiguration
ans = struct with fields:
    trainable: 1
         name: 'gaussian_noise_1'
       stddev: 1.5000

ans = struct with fields:
    trainable: 1
         name: 'gaussian_noise_2'
       stddev: 0.7000

Определите пользовательский уровень гауссова шума. Чтобы создать этот слой, сохраните файл gaussianNoiseLayer.m в текущей папке. Затем создайте два уровня шума Гаусса с теми же конфигурациями, что и импортированные слои Keras.

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

Замена слоев-заполнителей пользовательскими слоями с помощью replaceLayer.

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

Печать обновленного графика слоев с помощью plot.

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

Figure contains an axes. The axes with title Network with Replaced Layers contains an object of type graphplot.

Указать имена классов

Если импортированный слой классификации не содержит классов, их необходимо указать до прогнозирования. Если классы не указаны, то программа автоматически устанавливает классы на 1, 2, ..., N, где N - количество классов.

Найдите индекс классификационного слоя, просмотрев Layers свойство графа слоев.

lgraph.Layers
ans = 
  15x1 Layer array with layers:

     1   'input_1'                            Image Input             28x28x1 images
     2   'conv2d_1'                           Convolution             20 7x7x1 convolutions with stride [1  1] and padding 'same'
     3   'conv2d_1_relu'                      ReLU                    ReLU
     4   'conv2d_2'                           Convolution             20 3x3x1 convolutions with stride [1  1] and padding 'same'
     5   'conv2d_2_relu'                      ReLU                    ReLU
     6   'new_gaussian_noise_1'               Gaussian Noise          Gaussian noise with standard deviation 1.5
     7   'new_gaussian_noise_2'               Gaussian Noise          Gaussian noise with standard deviation 0.7
     8   'max_pooling2d_1'                    Max Pooling             2x2 max pooling with stride [2  2] and padding 'same'
     9   'max_pooling2d_2'                    Max Pooling             2x2 max pooling with stride [2  2] and padding 'same'
    10   'flatten_1'                          Keras Flatten           Flatten activations into 1-D assuming C-style (row-major) order
    11   'flatten_2'                          Keras Flatten           Flatten activations into 1-D assuming C-style (row-major) order
    12   'concatenate_1'                      Depth concatenation     Depth concatenation of 2 inputs
    13   'dense_1'                            Fully Connected         10 fully connected layer
    14   'activation_1'                       Softmax                 softmax
    15   'ClassificationLayer_activation_1'   Classification Output   crossentropyex

Классификационный слой имеет имя 'ClassificationLayer_activation_1'. Просмотрите классификационный слой и проверьте Classes собственность.

cLayer = lgraph.Layers(end)
cLayer = 
  ClassificationOutputLayer with properties:

            Name: 'ClassificationLayer_activation_1'
         Classes: 'auto'
    ClassWeights: 'none'
      OutputSize: 'auto'

   Hyperparameters
    LossFunction: 'crossentropyex'

Потому что Classes свойство слоя 'auto', необходимо указать классы вручную. Установите классы в значение 0, 1, ..., 9, а затем замените импортированный классификационный слой новым.

cLayer.Classes = string(0:9)
cLayer = 
  ClassificationOutputLayer with properties:

            Name: 'ClassificationLayer_activation_1'
         Classes: [0    1    2    3    4    5    6    7    8    9]
    ClassWeights: 'none'
      OutputSize: 10

   Hyperparameters
    LossFunction: 'crossentropyex'

lgraph = replaceLayer(lgraph,'ClassificationLayer_activation_1',cLayer);

Собрать сеть

Собрать график слоев с помощью assembleNetwork. Функция возвращает DAGNetwork объект, который готов к использованию для прогнозирования.

net = assembleNetwork(lgraph)
net = 
  DAGNetwork with properties:

         Layers: [15x1 nnet.cnn.layer.Layer]
    Connections: [15x2 table]
     InputNames: {'input_1'}
    OutputNames: {'ClassificationLayer_activation_1'}

См. также

| | | | | | |

Связанные темы