两个列表的逐元素乘法.张量在tensorflow中



在Tensorflow 2中,张量和数组之间进行元素乘法的最快方法是什么?

例如张量T(类型为tf.Tensor)为:

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

我们有一个数组a(类型为np。array):

[0, 1, 2]

我想有:

[[[0, 0],  
[0, 0]],  

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

[[0, 2],  
[4, 6]]]  

作为输出。

这叫做两个张量的外积。利用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)

在搜索结果

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

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

您可以遍历数组并使用张量值执行标量乘法:

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)

输出:

tf.Tensor(
[[[0 0]
[0 0]]
[[0 1]
[2 3]]
[[0 2]
[4 6]]], shape=(3, 2, 2), dtype=int32)

同样,您可以像下面这样使用列表推导来获得更多的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)

最新更新