Home > Back-end >  Multiply a 1D tensor with a 4D tensor in Tensorflow
Multiply a 1D tensor with a 4D tensor in Tensorflow

Time:10-01

I would like to make a calculation between 2 tensors: 1D tensor [batch_size, value] and 4D tensor [batch_size, L, W, D].

The calculation I would like to perform can be expressed in the following for-loop:

tensor1D = ... #shape = [batch_size, value]
tensor4D = ... #shape = [batch_size, L, W, D]
result = tensor4D

for i in range(batch_size):
    result[i] = tensor1D[i] * tensor4D[i]

return result

the result is what I would like to calculate

CodePudding user response:

According to the TensorFlow introduction to tensors, tensors are immutable (you can never update their content). What you want to look for is the tensordot operation, with this, you can probably create the tensor you want.

CodePudding user response:

You can first change the shape of tensor1D to the shape of tensor4D by using broadcast_to method, and then multiply it.

Try this:

batch_szie, l_size, w_size, d_size = 10, 2, 3, 4 # for example
tensor1D = tf.random.uniform((batch_szie,1))                    # shape = (10,1)
# the last dimension is 1, if it's not, uncomment below line
# tensor1D = tf.expand_dims(tensor1D, axis=-1)
tensor4D = tf.random.uniform((batch_szie,l_size,w_size,d_size)) # shape = (10,2,3,4)

# reshape tensor1D to the shape of tensor4D
tensor1D_converted = tf.reshape(
    tf.broadcast_to(tensor1D, [tensor4D.shape[0], tensor4D.shape[1]*tensor4D.shape[2]* tensor4D.shape[3]]), 
     tf.shape(tensor4D))

result = tf.multiply(tensor4D,tensor1D_converted)
return result
  • Related