[英]Create keras tensor with shape as same as model output for custom loss function
I have a keras model with output shape of the last layer is (None,574,6)
, which None
is my batch size feed into the model. I have a keras model with output shape of the last layer is
(None,574,6)
, which None
is my batch size feed into the model.
I also have a 2D numpy array called anchors
with shape (574,6)
.我还有一个二维 numpy 阵列,称为具有形状
(574,6)
的anchors
。
What I want is my output of each data minus that numpy array element wise.我想要的是每个数据的 output 减去 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
The above code occured the following error due to the batch_size is unknown.由于batch_size未知,上述代码出现以下错误。
InvalidArgumentError: Dimensions must be equal, but are 574 and 576 for 'sub_6' (op: 'Sub') with input shapes: [?,574,6], [576,4].
InvalidArgumentError:尺寸必须相等,但输入形状为 [?,574,6]、[576,4] 的“sub_6”(操作:“Sub”)的尺寸为 574 和 576。
During handling of the above exception, another exception occurred:
在处理上述异常的过程中,又出现了一个异常:
How can I repeat anchor_tensor
None
times to make its shape as the same as y_pred
?如何重复
anchor_tensor
None
次以使其形状与y_pred
相同?
Tensorflow will easily do what it calls "broadcasting", which is automatically repeating the missing elements if possible. Tensorflow 将轻松完成所谓的“广播”,如果可能的话,它会自动重复丢失的元素。 But for this to happen, it must confirm that the shapes allow that first.
但要做到这一点,它必须首先确认形状允许这样做。
The safest way to assure the shapes are compatible, is to make them have the same length, and have value 1 in the dimension you want it to repeat.确保形状兼容的最安全方法是使它们具有相同的长度,并且在您希望它重复的维度中具有值 1。
So, it's as simple as:所以,它很简单:
anchor_tensor = K.expand_dims(anchor_tensor, axis=0) #new shape is (1, 576, 4)
result = y_pred - anchor tensor
Now Tensorflow can match the shapes and will repeat the tensor for the entire batch size.现在 Tensorflow 可以匹配形状,并将重复整个批量大小的张量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.