如何在一层模块中打包多个keras层?

how to package several keras layers in one layer-module?

我必须从 pytorch 切换到 keras,在 pytorch 中我可以使用这样的代码创建类模块层:

from pytorch import nn

class up(nn.Module):
def __init__(self, in_ch, out_ch):
    super(up, self).__init__()
    self.up = nn.Upsample(scale_factor=2)
    self.conv = nn.Conv2D(in_ch, out_ch)
    # !!!! here two layers packaged in one
def forward(self, x1, x2):
    x1 = self.up(x1)
    x = t.cat([x2, x1], dim=1)
    x = self.conv(x)
    return x

如何在keras中以这种类似模块层的方式组织代码?

发现一种方法是执行函数:

def double_conv(var1, input):
    x = k.layers.Conv2d(some_parameters) (input)
    x = k.layers.Conv2d(some_parameters) (x)
    x = k.layers.MaxPooling2d(some_parameters) (x)
    return x

但还有更多 'kerasic' 方法吗?


编辑 这就是我一直在寻找使用像 Keras 层这样的函数的方法,但是如果有人能找到更好的方法来组织代码,那么我欢迎任何想法

def conv_bn_relu(filters, kernel=(3,3)):
    def inside(x):
        x = Conv2D(filters, kernel, padding='same') (x)
        x = BatchNormalization() (x)
        x = Activation('relu') (x)
        return x
    return inside

# usage:
x = conv_bn_relu(params) (x)

EDIT2
你甚至可以在 CamelCase 中作弊并命名这个函数,比如 类 所以它看起来像创建 Keras 一样层

def ConvBnRelu(filters, kernel=(3,3)):
    def inside(x):
        x = Conv2D(filters, kernel, padding='same') (x)
        x = BatchNormalization() (x)
        x = Activation('relu') (x)
        return x
    return inside

# usage:
x = ConvBnRelu(params) (x)

但可能第二种方案会被批评

最新的(截至 2021 年 6 月)Tensorflow documentation on creating custom layers 解释了如何做到这一点。

TL;DR:子类 tf.keras.layers.Layertf.keras.Model,如果您想检查自定义块内的中间结果,后者是首选。例如:

class ConvolutionalBlock1x1(tf.keras.Model):

  def __init__(self, filters):
    super().__init__(name='')

    self.conv2a = tf.keras.layers.Conv2D(filters, (1, 1))
    self.conv2b = tf.keras.layers.Conv2D(filters, (1, 1))
    self.conv2c = tf.keras.layers.Conv2D(filters, (1, 1))

  def call(self, input_tensor, training=False):
    x = self.conv2a(input_tensor)
    x = tf.nn.relu(x)
    x = self.conv2b(x)
    x = tf.nn.relu(x)
    x = self.conv2c(x)
    return tf.nn.relu(x)