Python 如何在一层模块中封装多个keras层?

Python 如何在一层模块中封装多个keras层?,python,machine-learning,neural-network,keras,keras-layer,Python,Machine Learning,Neural Network,Keras,Keras Layer,我必须从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) # !!

我必须从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 layer这样的函数的原因,但如果有人能找到更好的方法来组织代码,我会欢迎任何想法

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月)解释了如何做到这一点

TL;DR:子类
tf.keras.layers.Layer
tf.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)
 

差不多就是这样,尽管我通常不认为人们把keras作为k输入。查看应用程序中的网络以了解一些示例。他们中的一些人有预定义的模块,这些模块和你命名的模块差不多。你能给出一些具体的例子吗?例如,在
应用程序中。