[英]Element wise multiplication of two list that are tf.Tensor in tensorflow
What is the fastest way to do an element-wise multiplication between a tensor and an array in Tensorflow 2?在 Tensorflow 2 中,在张量和数组之间进行逐元素乘法的最快方法是什么?
For example, if the tensor T
(of type tf.Tensor) is:例如,如果张量T
(类型为 tf.Tensor)是:
[[0, 1],
[2, 3]]
and we have an array a
(of type np.array):我们有一个数组a
(类型为 np.array):
[0, 1, 2]
I wand to have:我想拥有:
[[[0, 0],
[0, 0]],
[[0, 1],
[2, 3]],
[[0, 2],
[4, 6]]]
as output.作为输出。
What you describe is the outer product of two tensors.你描述的是两个张量的外积。 This can be expressed simply using Tensorflow's broadcasting rules.这可以简单地使用 TensorFlow 的广播规则来表达。
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)>
In tensorflow , we have tf.tensordot
and can use this like below:在tensorflow中,我们有tf.tensordot
并且可以像下面这样使用它:
>>> 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)>
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:此外,您可以按如下方式使用列表推导来获得更具readable
的代码:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.