简体   繁体   English

tensorflow/keras 中的自定义层 - 这两个选项是否相等?

[英]Custom layers in tensorflow/keras - are these two options equal?

According to https://www.tensorflow.org/guide/keras/custom_layers_and_models#layers_are_recursively_composable custom layers in tensorflow2 / keras can be defined like this根据https://www.tensorflow.org/guide/keras/custom_layers_and_models#layers_are_recursively_composable custom layers in tensorflow2 / Z063009BB15C8272CF2ZB0C7 可以这样定义

class CustomLayer(layers.Layer):
    def __init__(self, ntimes):
        super().__init__()
        self.convs = [layers.Conv2D(10, (3, 3),  padding='same') for i in range(ntimes)]

    def call(self, x, **kwargs):
        for conv in self.convs:
            x = conv(x)
        return x

However, recently I came across another notation:但是,最近我遇到了另一种表示法:

def CustomLayer(ntimes):
    def layer(x):
        for i in range(ntimes):
            x = layers.Conv2D(10, (3, 3), padding='same')(x)
        return x

    return layer

Obviously it's not an instance of the Layer-class, but the resulting operations seem to be identical.显然它不是 Layer 类的实例,但结果操作似乎是相同的。 Or am I missing something?还是我错过了什么? Are there any downsides to this approach?这种方法有什么缺点吗?


Ps: Such layers would be used in the following exemplary context: Ps:这样的层将在以下示例性上下文中使用:

xin = layers.Input((10,10,3))
layer = CustomLayer(5)
xout = layer(xin)
model = models.Model(xin, xout)
model.summary()

In my opinion, what you are doing is creating a block of Layers with predefined functionality instead of creating a new Custom Layer.在我看来,您正在做的是创建一个具有预定义功能的图层块,而不是创建一个新的自定义图层。 To elaborate you could make individual access to each layer in the block and hence it's not a Layer.为了详细说明,您可以单独访问块中的每一层,因此它不是层。 Creating blocks can be done using both but in case you want to implement your own functions inside a layer or some modification like printing the results of that layer at each epoch or something else to that particular layer such then you would need to use the first method.创建块可以使用两者来完成,但如果您想在层内实现自己的功能或进行一些修改,例如在每个时期打印该层的结果或其他特定层的结果,那么您需要使用第一种方法.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM