通过循环操作两个张量

时间:2018-07-12 20:49:46

标签: python tensorflow

假设在普通的python中,我有两个列表:A = [1, 2, 3]B = [4, 5, 6]。现在,我可以创建一个名为C = [4, 5, 6, 8, 10, 12, 12, 15, 18]的新列表。我可以通过

轻松获得此结果
C = list()
for a in A:
    for b in B:
        C.append(a * b)

如果ABtensorflow中的张量,那么如上所述,有什么方法可以得到张量C吗?

2 个答案:

答案 0 :(得分:1)

这里有两个选项:

设置:

A = tf.constant([1, 2, 3])
B = tf.constant([4, 5, 6])
tf.InteractiveSession()

1)通过广播-

tf.reshape(tf.reshape(A, (-1,1)) * B, (-1,)).eval()
# array([ 4,  5,  6,  8, 10, 12, 12, 15, 18], dtype=int32)

# reshape A to 2d array
tf.reshape(A, (-1,1)).eval()

#array([[1],
#       [2],
#       [3]], dtype=int32)

# multiply with B
(tf.reshape(A, (-1,1)) * B).eval()

#array([[ 4,  5,  6],
#       [ 8, 10, 12],
#       [12, 15, 18]], dtype=int32)

平移上面的张量可以满足您的需求。

2)使用einsum-

tf.reshape(tf.einsum('i,j->ij', A, B), (-1,)).eval()
# array([ 4,  5,  6,  8, 10, 12, 12, 15, 18], dtype=int32)

# use einsum to calculate the outer product

tf.einsum('i,j->ij', A, B).eval()
#array([[ 4,  5,  6],
#       [ 8, 10, 12],
#       [12, 15, 18]], dtype=int32)

答案 1 :(得分:1)

这是另一个示例,该示例使用tf.map_fn()巧妙地在Tensor上迭代,并使用tf.stack()将列表元素转换回Tensor。

A = tf.constant([1, 2, 3])
B = tf.constant([4, 5, 6])

with tf.Session() as sess:
    tf.global_variables_initializer().run()

    C = list()
    for a in tf.map_fn(lambda x: x, A).eval():
        for b in tf.map_fn(lambda x: x, B).eval():
            C.append(a * b)
    C = tf.stack(C)

    print(C.eval())

'Output':
[ 4  5  6  8 10 12 12 15 18]