我正在尝试在TensorFlow中实现SOLO架构的实例分割(解耦版本)。
https://arxiv.org/pdf/1912.04488.pdf
目前,我需要计算损失函数,并将第一个conv2d层的每个输出图与第二个层的输出图相乘。
xi = Conv2D(…)(input) # 输出为 (batch, None, None, 24)yi = Conv2D(…)(input) # 输出为 (batch, None, None, 24)
我需要将xi
的每个输出图(逐元素)与yi
相乘,以获得(batch, None, None, 24*24)
的输出。我需要将第一个conv2d的单个输出特征图与第二个conv2d层的全部特征图进行逐元素乘法,依此类推。这就是为什么是24 * 24的原因。
我尝试使用for循环来实现这一点,但得到了错误:
OperatorNotAllowedInGraphError: iterating over tf.Tensor is not allowed: AutoGraph did convert this function.
有什么建议可以使用一些TF2操作来实现这一点吗?
回答:
这基本上是最后一个维度的外积,然后将最后两个维度折叠。表达这个操作的简短方法是使用tf.repeat
和tf.tile
。
#channel_dims是最后一个维度的长度,即你在问题中的24 @tf.functiondef outerprodflatten(x,y,channel_dims): return tf.repeat(x,channel_dims,-1)*tf.tile(y,[1,1,1,channel_dims])
要在函数式API中使用这个,你还需要定义一个自定义的keras层或lambda层,例如
class Outerprodflatten_layer(tf.keras.layers.Layer): def __init__(self, channel_dims): self.channel_dims = channel_dims super().__init__() def call(self, inputs): return tf.repeat(inputs[0],self.channel_dims,-1)*tf.tile(inputs[1],[1,1,1,self.channel_dims])x = Conv2D(…)(input) # 输出为 (batch, None, None, 24)y = Conv2D(…)(input) # 输出为 (batch, None, None, 24)out=Outerprodflatten_layer(24)([x,y])