tf.stack = tf.expand_dims + tf.concat
>>> t1 = tf.constant([[1, 2, 3], [4, 5, 6]])
>>> t2 = tf.constant([[7, 8, 9], [10, 11, 12]])
>>> c0=tf.stack([t1, t2], 0)
>>> c1=tf.stack([t1, t2], 1)
>>> c2=tf.stack([t1, t2], 2)
>>> with tf.Session() as sess:
... print('c0')
... print(sess.run(c0))
... print('c1')
... print(sess.run(c1))
... print('c2')
... print(sess.run(c2))
//结果如下:
c0
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
c1
[[[ 1 2 3]
[ 7 8 9]]
[[ 4 5 6]
[10 11 12]]]
c2
[[[ 1 7]
[ 2 8]
[ 3 9]]
[[ 4 10]
[ 5 11]
[ 6 12]]]
>>> d1=tf.concat([tf.expand_dims(t1, axis=1), tf.expand_dims(t2, axis=1)], 1)
>>> d0=tf.concat([tf.expand_dims(t1, axis=0), tf.expand_dims(t2, axis=0)], 0)
>>> d2=tf.concat([tf.expand_dims(t1, axis=2), tf.expand_dims(t2, axis=2)], 2)
>>> with tf.Session() as sess:
... print('d0')
... print(sess.run(d0))
... print('d1')
... print(sess.run(d1))
... print('d2')
... print(sess.run(d2))
//结果如下:
d0
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
d1
[[[ 1 2 3]
[ 7 8 9]]
[[ 4 5 6]
[10 11 12]]]
d2
[[[ 1 7]
[ 2 8]
[ 3 9]]
[[ 4 10]
[ 5 11]
[ 6 12]]]