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

Question:

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.

Asked By: Loris Pilotto

||

Answers:

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)
Answered By: Cardstdani

This is called the outer product of two tensors. It’s easy to compute by taking advantage of 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)>
Answered By: Brian

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)>
Answered By: I'mahdi