sebjwallace
sebjwallace

Reputation: 795

tensorflow Multiplying tensors of different shapes

In tensorflow, If I had a tensors:

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

How can I multiply them so that I get the resulting tensor with shape [3,2,2]?

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

My multiplication factors are simple here for demonstration.

Upvotes: 1

Views: 1015

Answers (1)

akuiper
akuiper

Reputation: 214957

Reshape B to (3,1,1) so that A and B have the same number of dimensions and then do multiplication. tf.multiply supports broadcasting so dimension with size 1 in B will be broadcasted and multiplied with all elements in corresponding dimension in A:

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

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

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

#        [[6, 6],
#         [6, 6]]], dtype=int32)

Upvotes: 1

Related Questions