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:
JavaScript
x
3
1
[[0, 1],
2
[2, 3]]
3
and we have an array a
(of type np.array):
JavaScript
1
2
1
[0, 1, 2]
2
I wand to have:
JavaScript
1
9
1
[[[0, 0],
2
[0, 0]],
3
4
[[0, 1],
5
[2, 3]],
6
7
[[0, 2],
8
[4, 6]]]
9
as output.
Advertisement
Answer
This is called the outer product of two tensors. It’s easy to compute by taking advantage of Tensorflow’s broadcasting rules:
JavaScript
1
12
12
1
import numpy as np
2
import tensorflow as tf
3
4
t = tf.constant([[0, 1],[2, 3]])
5
a = np.array([0, 1, 2])
6
7
# (2,2) x (3,1,1) produces the desired shape of (3,2,2)
8
result = t * a.reshape((-1, 1, 1))
9
# Alternatively: result = t * a[:, np.newaxis, np.newaxis]
10
11
print(result)
12
results in
JavaScript
1
10
10
1
<tf.Tensor: shape=(3, 2, 2), dtype=int32, numpy=
2
array([[[0, 0],
3
[0, 0]],
4
5
[[0, 1],
6
[2, 3]],
7
8
[[0, 2],
9
[4, 6]]], dtype=int32)>
10