为自定义损失函数创建形状与模型输出相同的 keras 张量

Create keras tensor with shape as same as model output for custom loss function

我有一个 keras 模型,最后一层的输出形状是 (None,574,6)None 是我输入模型的批量大小。

我还有一个名为 anchors 的二维 numpy 数组,形状为 (574,6)

我想要的是每个数据的输出减去 numpy 数组元素。

import keras.backend as K

anchor_tensor = K.cast(anchors, tf.float32)
print(K.int_shape(anchor_tensor))
#(576, 4)
print(K.int_shape(y_pred))
#(None, 574, 6)
y_pred - anchor_tensor

由于batch_size未知,上述代码出现了以下错误。

InvalidArgumentError: Dimensions must be equal, but are 574 and 576 for 'sub_6' (op: 'Sub') with input shapes: [?,574,6], [576,4].

During handling of the above exception, another exception occurred:

如何重复anchor_tensorNone次使其形状与y_pred相同?

Tensorflow 会很容易地完成它所谓的 "broadcasting",它会在可能的情况下自动重复缺失的元素。但要做到这一点,它必须首先确认形状允许这样做。

确保形状兼容的最安全方法是使它们具有相同的长度,并且在您希望其重复的维度中具有值 1。

所以,很简单:

anchor_tensor = K.expand_dims(anchor_tensor, axis=0) #new shape is (1, 576, 4)   
result = y_pred - anchor tensor

现在 Tensorflow 可以匹配形状并且会为整个批量大小重复张量。