[英]Add 2 tensors with different rank
I have 2 tensors: A with shape of (None, 16, 7, 7, 1024)
and B with shape of (1, 16, 7, 7, 1024)
.我有 2 个张量:A 的形状为
(None, 16, 7, 7, 1024)
和 B 的形状为(1, 16, 7, 7, 1024)
。 I add these tensors using keras.layers.add([A, B])
.我使用
keras.layers.add([A, B])
添加这些张量。 I expect to have a tensor with shape of ( None , 16, 7, 7, 1024) but I got ( 1 , 16, 7, 7, 1024) ==> notice that batch size now becomes 1. How to get the result as I want ( None
)?我希望有一个形状为 ( None , 16, 7, 7, 1024) 的张量,但我得到了 ( 1 , 16, 7, 7, 1024) ==> 注意批量大小现在变为 1。如何获得结果如我所愿(
None
)?
Code:代码:
_h_state = np.zeros((16, 7, 7, 1024))
h_state = Input(tensor=tf.constant(_h_state, dtype=tf.float32), name='input_h_state')
enc = encoder.output
enc_x = Conv3D(filters=256, kernel_size=(1, 1, 1), strides=(1, 1, 1), name='enc_conv')(enc)
h_state_expanded = Lambda(lambda x: K.expand_dims(x, 0))(h_state)
h_state_x = Conv3D(filters=256, kernel_size=(1, 1, 1), strides=(1, 1, 1), name='h_state_conv')(h_state_expanded)
x = layers.add([enc_x, h_state_x])
x = Activation('tanh')(x)
.
.
.
When you print x.shape
, the output is (None, 16, 7, 7, 1024)
, but interestingly both plot_model
and model.summary
show the "unbroadcast" first dimension.当您打印
x.shape
,输出为(None, 16, 7, 7, 1024)
,但有趣的是plot_model
和model.summary
显示“未广播”第一维。
I believe you are right - the method keras.layers._Merge.compute_output_shape
might not be handling broadcasting correctly for the first dimension in this particular case.我相信您是对的 - 在这种特殊情况下,
keras.layers._Merge.compute_output_shape
方法可能无法正确处理第一维的广播。 That is something that should probably be fixed via a pull request.这可能应该通过拉取请求来修复。
In the meantime, you can instead use:同时,您可以改为使用:
x = Lambda(lambda x: x[0] + x[1])([enc_x, h_state_x])
which gives the expected output shape.这给出了预期的输出形状。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.