Python 通过循环操纵两个张量
假设在普通python中,我有两个列表:Python 通过循环操纵两个张量,python,tensorflow,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) 如果A和B是tensorflow中的张量,那么有没有办法像我上面描述的那样获得张量C 设立: 1) 通过广播- tf.reshape(tf.reshape(A, (-1,1))
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)
如果A
和B
是tensorflow
中的张量,那么有没有办法像我上面描述的那样获得张量C
设立:
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) 通过广播-
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)
下面是另一个例子,使用
tf.map\u fn()
巧妙地迭代张量,并使用tf.stack()
将列表元素转换回张量
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]
下面是另一个例子,使用
tf.map\u fn()
巧妙地迭代张量,并使用tf.stack()
将列表元素转换回张量
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]
你让我开心!你让我开心!