使用Tensorflow 2.0中的图层子类在我的自定义图层中获取此错误,“必须始终传递`Layer.call`的第一个参数。”

问题描述 投票:0回答:1

我使用Tensorflow 2.0图层子类化的图层来制作此自定义图层。我正在尝试制作一层残留块。但是,当我通过顺序API在模型中添加此自定义层时,以下错误。

class ResidualBlock(Layer):

    def __init__(self, **kwargs):
        super(ResidualBlock, self).__init__(**kwargs)

    def build(self, input_shape):
        """
        This method should build the layers according to the above specification. Make sure 
        to use the input_shape argument to get the correct number of filters, and to set the
        input_shape of the first layer in the block.
        """
        self.bn_1 = BatchNormalization(input_shape=input_shape)
        self.conv_1 = Conv2D( input_shape[0],(3,3), padding='SAME')
        self.bn_2 = BatchNormalization()
        self.conv_2 = Conv2D( input_shape[0],(3,3), padding='SAME')






    def call(self, inputs, training=False):
        """
        This method should contain the code for calling the layer according to the above
        specification, using the layer objects set up in the build method.
        """
        h = self.bn_1(training=True)(inputs)
        h = tf.nn.relu(h)
        h = self.conv_1(h)
        h = self.bn_2(training=True)(h)
        h = tf.nn.relu(h)
        h = self.conv_2(h)
        return Add(inputs, h)

但是当我初始化该层时,我得到了错误。

test_model = tf.keras.Sequential([ResidualBlock(input_shape=(28, 28, 1), name="residual_block")])
test_model.summary()

我的错误日志:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-13-991ed1d78e4b> in <module>()
      1 # Test your custom layer - the following should create a model using your layer
      2 
----> 3 test_model = tf.keras.Sequential([ResidualBlock(input_shape=(28, 28, 1), name="residual_block")])
      4 test_model.summary()

5 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/autograph/impl/api.py in wrapper(*args, **kwargs)
    263       except Exception as e:  # pylint:disable=broad-except
    264         if hasattr(e, 'ag_error_metadata'):
--> 265           raise e.ag_error_metadata.to_exception(e)
    266         else:
    267           raise

ValueError: in user code:

    <ipython-input-12-3beea3ca10b0>:32 call  *
        h = self.bn_1(training=True)(inputs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py:800 __call__  **
        'The first argument to `Layer.call` must always be passed.')

    ValueError: The first argument to `Layer.call` must always be passed.
python tensorflow tensorflow2.0 keras-layer
1个回答
0
投票

在调用方法期间,将批处理规范的前向传递更改为h=self.bn_1(inputs)。因为您要为整个层传递training=True,所以Tensorflow将自动照顾所有子层保持相同的标志,而无需为每个子层显式传递它。但是,如果您的应用程序想要与其他层相比以不同的方式控制批处理规范,请使用h=self.bn_1(inputs, training=True)。您的最终归还声明格式不正确,应类似于Add()[inputs, h]

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.