如何在 Keras 中的卷积层之间添加跳过连接
How to add skip connection between convolutional layers in Keras
我想在keras中的残差块之间添加一个跳跃连接。这是我当前的实现,它不起作用,因为张量具有不同的形状。
函数如下所示:
def build_res_blocks(net, x_in, num_res_blocks, res_block, num_filters, res_block_expansion, kernel_size, scaling):
net_next_in = net
for i in range(num_res_blocks):
net = res_block(net_next_in, num_filters, res_block_expansion, kernel_size, scaling)
# net tensor shape: (None, None, 32)
# x_in tensor shape: (None, None, 3)
# Error here, net_next_in should be in the shape of (None, None, 32) to be fed into next layer
net_next_in = Add()([net, x_in])
return net
我得到的错误是:ValueError: Operands could not be broadcast together with shapes (None, None, 32) (None, None, 3)
我的问题是如何将这些张量添加或合并为正确的形状 (None、None、32)。如果这不是正确的方法,你怎么能达到预期的结果?
编辑:
这就是 res_block 的样子:
def res_block(x_in, num_filters, expansion, kernel_size, scaling):
x = Conv2D(num_filters * expansion, kernel_size, padding='same')(x_in)
x = Activation('relu')(x)
x = Conv2D(num_filters, kernel_size, padding='same')(x)
x = Add()([x_in, x])
return x
你不能添加不同形状的张量。您可以将它们与 keras.layers.Concatenate 连接起来,但这会使您得到形状为 [None, None, 35]
.
的张量
或者,看看
Resnet50 在 Keras 中实现。他们的残差块在快捷方式中具有 1x1xC 卷积,用于那些要添加的维度不同的情况。
我想在keras中的残差块之间添加一个跳跃连接。这是我当前的实现,它不起作用,因为张量具有不同的形状。
函数如下所示:
def build_res_blocks(net, x_in, num_res_blocks, res_block, num_filters, res_block_expansion, kernel_size, scaling):
net_next_in = net
for i in range(num_res_blocks):
net = res_block(net_next_in, num_filters, res_block_expansion, kernel_size, scaling)
# net tensor shape: (None, None, 32)
# x_in tensor shape: (None, None, 3)
# Error here, net_next_in should be in the shape of (None, None, 32) to be fed into next layer
net_next_in = Add()([net, x_in])
return net
我得到的错误是:ValueError: Operands could not be broadcast together with shapes (None, None, 32) (None, None, 3)
我的问题是如何将这些张量添加或合并为正确的形状 (None、None、32)。如果这不是正确的方法,你怎么能达到预期的结果?
编辑:
这就是 res_block 的样子:
def res_block(x_in, num_filters, expansion, kernel_size, scaling):
x = Conv2D(num_filters * expansion, kernel_size, padding='same')(x_in)
x = Activation('relu')(x)
x = Conv2D(num_filters, kernel_size, padding='same')(x)
x = Add()([x_in, x])
return x
你不能添加不同形状的张量。您可以将它们与 keras.layers.Concatenate 连接起来,但这会使您得到形状为 [None, None, 35]
.
或者,看看 Resnet50 在 Keras 中实现。他们的残差块在快捷方式中具有 1x1xC 卷积,用于那些要添加的维度不同的情况。