Home > Enterprise >  Element wise multiplication of two list that are tf.Tensor in tensorflow
Element wise multiplication of two list that are tf.Tensor in tensorflow

Time:06-26

What is the fastest way to do an element-wise multiplication between a tensor and an array in Tensorflow 2?

For example, if the tensor T (of type tf.Tensor) is:

[[0, 1],  
[2, 3]]

and we have an array a (of type np.array):

[0, 1, 2]

I wand to have:

[[[0, 0],  
  [0, 0]],  
  
 [[0, 1],  
  [2, 3]],  
 
 [[0, 2],  
  [4, 6]]]  

as output.

CodePudding user response:

In , we have tf.tensordot and can use this like below:

>>> a = tf.reshape(tf.range(4), (2,2))
>>> b = tf.range(3)
>>> tf.tensordot(b,a, axes=0)
<tf.Tensor: shape=(3, 2, 2), dtype=int32, numpy=
array([[[0, 0],
        [0, 0]],

       [[0, 1],
        [2, 3]],

       [[0, 2],
        [4, 6]]], dtype=int32)>

CodePudding user response:

You can traverse the array and perform a scalar multiplication with the tensor values:

import tensorflow as tf

t = tf.constant([[0, 1],[2, 3]])
a = [0, 1, 2]

u = []
for i in a:
    u.append(t.numpy()*i)
u = tf.constant(u)
print(u)

Output:

tf.Tensor(
[[[0 0]
  [0 0]]

 [[0 1]
  [2 3]]

 [[0 2]
  [4 6]]], shape=(3, 2, 2), dtype=int32)

Also, you can use list comprehension as follows to get a more readable code:

import tensorflow as tf

t = tf.constant([[0, 1],[2, 3]])
a = [0, 1, 2]

u = tf.constant([t.numpy()*i for i in a])
print(u)

CodePudding user response:

What you describe is the outer product of two tensors. This can be expressed simply using Tensorflow's broadcasting rules.

import numpy as np
import tensorflow as tf

t = tf.constant([[0, 1],[2, 3]]) 
a = np.array([0, 1, 2])

# (2,2) x (3,1,1) produces the desired shape of (3,2,2)
result = t * a.reshape((-1, 1, 1))
# Alternatively: result = t * a[:, np.newaxis, np.newaxis]

print(result)

results in

<tf.Tensor: shape=(3, 2, 2), dtype=int32, numpy=
array([[[0, 0],
        [0, 0]],

       [[0, 1],
        [2, 3]],

       [[0, 2],
        [4, 6]]], dtype=int32)>
  • Related