繁体   English   中英

tensorflow 中 tf.Tensor 的两个列表的元素乘法

[英]Element wise multiplication of two list that are tf.Tensor in 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)>

中,我们有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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM