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

Issue

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.

Solution

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)>

Answered By – Brian

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published