tf.concat与tf.stack(仅个人理解)
tf.concat是沿某一维度拼接shape相同的张量,拼接生成的新张量维度不会增加。而tf.stack是在新的维度上拼接,拼接后维度加1
例如:
import tensorflow as tf
a = tf.constant([[1,2,3],[4,5,6]])
b = tf.constant([[7,8,9],[10,11,12]])
ab1 = tf.concat([a,b],axis=0)
ab2 = tf.stack([a,b], axis=0)
sess = tf.Session()
print(sess.run(ab1))
print(sess.run(ab2))
print ab1
print ab2
结果:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]#ab1的值
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]#ab2的值
Tensor(“concat:0”, shape=(4, 3), dtype=int32)#ab1的属性
Tensor(“stack:0”, shape=(2, 2, 3), dtype=int32)#ab2的属性
由上可知:由于axis=0,表示在第一维连接。对tf.concat来说连接后张量的第一维是在外层中括号内,将两个张量原来所有第一维内的元素(如[1 2 3],[7 8 9 ]等)连接。而tf.stack需要先将原二维张量扩展成三维张量,在扩展后张量的第一维上将原两个二维张量连接。
若axis=1,结果为:
[[ 1 2 3 7 8 9]
[ 4 5 6 10 11 12]]
[[[ 1 2 3]
[ 7 8 9]]
[[ 4 5 6]
[10 11 12]]]
Tensor(“concat:0”, shape=(2, 6), dtype=int32)
Tensor(“stack:0”, shape=(2, 2, 3), dtype=int32)
同上:axis=1,表示在第二维连接。对tf.concat来说连接后张量的第二维是在内层中括号内,将两个张量原来所有第二维内的元素(如1 ,2, 3,7,8,9等)连接。tf.stack先将原二维张量扩展成三维张量,在扩展后张量的第二维上将两个原张量的相对应的元素(如[1 2 3]和[ 7 8 9])连接。
若axis=2,tf.concat会报错(因为tf.concat不增加维数)。tf.stack结果如下:
[[[ 1 7]
[ 2 8]
[ 3 9]]
[[ 4 10]
[ 5 11]
[ 6 12]]]
Tensor(“stack:0”, shape=(2, 3, 2), dtype=int32)
同上:axis=2,表示在第三维连接。tf.stack先将原二维张量扩展成三维张量,在扩展后张量的第三维上将两个原张量的相对应的元素(如1和7,2和8,3和9等 )连接。