gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:29:58 25 4
gpt4 key购买 nike

我必须从 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)

但可能第二种解决方案会受到批评

关于python - 如何在一层模块中打包多个keras层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49467127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com