假设在TensorFlow中定义了以下三个张量(形状相同)。
A = [[1,2,3],[4,5,6],[7,8,9]]
B = [[10,11,12],[13,14,15],[16,17,18]]
C = [[19,20,21],[22,23,24],[25,26,27]]
目标是创建具有以下形式的张量D
D = [[1,2,3],[10,11,12],[19,20,21],[4,5,6],[13,14,15],[22,23,24],[7,8,9],[16,17,18],[25,26,27]]
快速而有效的方法是什么?
在此手术中将如何发生反向传播?
答案 0 :(得分:1)
我的尝试是这样。如果我采用给定的形状,那么将产生所需的输出。
A = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = tf.constant([[10, 11, 12], [13, 14, 15], [16, 17, 18]])
C = tf.constant([[19, 20, 21], [22, 23, 24], [25, 26, 27]])
with tf.Session() as sess :
sess.run(tf.global_variables_initializer())
ODD = tf.concat( [A[0::2],B[0::2],C[0::2]], axis=0)
EVENANDODD = tf.concat([ODD[0::2],
tf.concat([A[1::2], B[1::2], C[1::2]], axis=0)], axis=0)
FINAL = tf.concat([EVENANDODD,
ODD[1::2]], axis=0)
print( sess.run(FINAL) )
[[1 2 3] [10 11 12] [19 20 21] [4 5 6] [13 14 15] [22 23 24] [7 8 9] [16 17 18] [25 26 27]]
注意:我无法解决反向传播和性能方面的问题。
答案 1 :(得分:0)
在您的特定情况下,A,B,C是3x3矩阵,而您想要一个9x3矩阵。最直观的方法是连接它们。下面我用numpy展示它。
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.array([[10, 11, 12], [13, 14, 15], [16, 17, 18]])
c = np.array([[19, 20, 21], [22, 23, 24], [25, 26, 27]])
abc = np.concatenate((a, b, c), axis=0)
abc = abc.reshape((3, 3, 3))
abc = abc.transpose((1, 0, 2))
abc = abc.reshape((9, 3)) # this gives your objective
但是,通常来说,您可能想从每个矩阵中堆叠不规则的行,例如[A0,B2,A2,A1,C1,C2,B0,C0,B1]。 tf.gather
是一个选择。
import tensorflow as tf
a = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = tf.constant([[10, 11, 12], [13, 14, 15], [16, 17, 18]])
c = tf.constant([[19, 20, 21], [22, 23, 24], [25, 26, 27]])
abc = tf.concat((a, b, c), axis=0)
abc = tf.gather(abc, [0, 5, 2, 1, 7, 8, 3, 5, 6, 4], axis=0)
sess = tf.InteractiveSession()
print(sess.run(abc))
如果没记错的话,在tf.gather中,可以反向执行反向传播。 a,b,c的元素(仅为1或0),而不是w.r.t.索引(在这种情况下为[0, 5, 2, 1, 7, 8, 3, 5, 6, 4]
)。