Пользовательский слой keras не отображается в модели.сводка

#tensorflow #keras

#tensorflow #keras

Вопрос:

Когда я пытаюсь просмотреть .summary мою модель с помощью моих пользовательских слоев, я получаю следующие результаты:

 Model: "functional_29"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_118 (InputNode)           [(None, 1)]          0                                            
__________________________________________________________________________________________________
input_119 (InputNode)           [(None, 1)]          0                                            
__________________________________________________________________________________________________
tf_op_layer_strided_slice_156 ( [(1,)]               0           input_118[0][0]                  
__________________________________________________________________________________________________
tf_op_layer_strided_slice_157 ( [(1,)]               0           input_119[0][0]                  
__________________________________________________________________________________________________
input_120 (InputNode)           [(None, 1)]          0                                            
_________________________________________________________________________________________________   
tf_op_layer_concat_106 (TensorF [(2,)]               0           tf_op_layer_strided_slice_162[0][
                                                                 tf_op_layer_strided_slice_163[0][

...
__________________________________________________________________________________________________
tf_op_layer_strided_slice_164 ( [(1,)]               0           input_120[0][0]                  
__________________________________________________________________________________________________
tf_op_layer_node_128_output (Te [()]                 0           tf_op_layer_Relu_55[0][0]        
==================================================================================================
Total params: 0
Trainable params: 0
Non-trainable params: 0
__________________________________________________________________________________________________
  

Почему это так? Как я могу обернуть все эти операции под меткой MyLayer ?

Комментарии:

1. Вы действительно создали пользовательский слой (подкласс Layer)? Без кода ответить особо не на что.

Ответ №1:

Вы можете создать свой собственный слой, создав подкласс из tf.keras.layers.Layer .

 import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Input

class DirectLayer(tf.keras.layers.Layer):
    
  def __init__(self, name = "direct_layer", **kwargs):
    super(DirectLayer, self).__init__(name=name, **kwargs)

  def build(self, input_shape):
    self.w = self.add_weight(
            shape=input_shape[1:],
            initializer="random_normal",
            trainable=True,
        )
    self.b = self.add_weight(
        shape=input_shape[1:], initializer="random_normal", trainable=True
    )

    
  def call(self, inputs):
      return tf.multiply(inputs, self.w)   self.b

x_in = Input(shape=[10])
x = DirectLayer(name="my_layer")(x_in)
x_out = DirectLayer()(x)

model = Model(x_in, x_out)

x = tf.ones([16,10])
tf.print(model(x))

tf.print(model.summary())
  

Я создал простой слой под названием DirectLayer. Я построил модель, которая использует этот слой дважды. Входной слой существует только для указания формы входных данных.

Как вы можете видеть, вы можете легко указать имя слоя.

Функция summary выдает следующее:

 Model: "functional_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         [(None, 10)]              0         
_________________________________________________________________
my_layer (DirectLayer)       (None, 10)                20        
_________________________________________________________________
direct_layer (DirectLayer)   (None, 10)                20        
=================================================================
Total params: 40
Trainable params: 40
Non-trainable params: 0
_________________________________________________________________
None