Home > Blockchain >  Multiply 3D Tensors Matrix by Matrix in Tensorflow
Multiply 3D Tensors Matrix by Matrix in Tensorflow

Time:02-02

Let's say I have 2 3D Tensors a and b. I need to compute the Tensor that, in position i has the multiplication of the ith matrix of a by the ith matrix of b. It would be equivalent to this:

a = tf.random.uniform([3,7,10])
b = tf.random.uniform([3,10,5])
#c is a tensor with shape (,7,5)
for i in range(len(a)):
 c = c.concat((c,a[i]@b[i]),0)

What is the correct way to do this in Tensorflow?

CodePudding user response:

You do not have to use a for loop at all:

import tensorflow as tf
tf.random.set_seed(56)

a = tf.random.uniform([3,7,10])
b = tf.random.uniform([3,10,5])
c = a@b
print(c.shape)
# (3, 7, 5)
  •  Tags:  
  • Related