tensorflow乘以不同形状的张量

时间:2019-02-15 16:13:58

标签: python tensorflow

在张量流中,如果我有张量:

A = tf.fill([3,2,2],2) # shape [3,2,2]
B = tf.constant([1,2,3]) # shape [3]

如何将它们相乘,以便得到形状为[3,2,2]的张量?

[
  [ [2,2], [2,2] ],
  [ [4,4], [4,4] ],
  [ [6,6], [6,6] ]
]

我的乘法因子在这里很容易演示。

1 个答案:

答案 0 :(得分:1)

B重塑为(3,1,1),以使AB的维数相同,然后相乘。 tf.multiply支持broadcasting,因此1中尺寸为B的维度将被广播并与A中相应维度的所有元素相乘:

(A * tf.reshape(B, (3,1,1))).eval()

# array([[[2, 2],
#         [2, 2]],

#        [[4, 4],
#         [4, 4]],

#        [[6, 6],
#         [6, 6]]], dtype=int32)
相关问题