我必须从 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)
但可能第二种解决方案会受到批评
