前言
很多博客只是把stack()函数的维度变化做了说明,但是在高维中axis取值对数据组织方式的变化并没有说明清楚。本文结合例子和图片对此进行了详细说明。
函数参数
stack(values, axis=0, name='stack')
Args:
values: 一个张量的列表,里面的张量必须有相同的shape和dtype
axis: 整数,指定堆叠的维度,为-1时表示在最后一维堆叠
name: A name for this operation (optional).
Returns:
output: A stacked `Tensor` with the same type as `values`.
该函数与**numpy.stack()功能相同;
与tf.concat()**不同之处在于:stack会增加一个维度,concat保持原维度不变;stack只能堆叠shape相同的张量,concat则不一定。
例子说明
import tensorflow as tf
a = tf.constant([[1,2,3],[4,5,6]],dtype=tf.float32)
b = tf.constant([[7,8,9],[10,11,12]],dtype=tf.float32)
c0 = tf.stack([a,b], axis=0)
c1 = tf.stack([a,b], axis=1)
c2 = tf.stack([a,b], axis=2)
with tf.Session() as sess:
print(sess.run([c0, tf.shape(c0)]))
print(sess.run([c1, tf.shape(c1)]))
print(sess.run([c2, tf.shape(c2)]))
结果:
c0,shape=(2,2,3)
c1, shape=(2,2,3)
c2, shape=(2,3,2)
加粗的为新增的维度所在位置,用图片表示如下:
原始张量 a, b。numpy和tf中数据都是按行组织的,所以每行颜色相同,数据再组织的原则也是:以原始行数据为基本单元进行拼接。
(1)axis=0时,相当于在batch上做堆叠,即batch数增多,原来数据组织方式不变。
(2)axis=1时,将原来的(2,3)数据拆解为:(2, insert, 3)。表示为2个batch,insert行,3列。取a和b中相同的行,并沿着行的方向(axis=1)进行拼接。
(3)axis=2时,即拆解为(2,3, insert)。同样,取a,b中相同的行,但沿着列的方向(axis=2)进行拼接。
看着图片理解就很明白了。