介绍
将 r 维的list 堆叠 成 r+1 维
语法
tf.stack(
values,
axis=0,
name='stack'
)
参数:
- values:list类型,其元素是Tensor(shape和dtype都相同)
- axis:按照哪个轴堆叠。默认第1个轴
例子
一维数组
x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])
测试代码
a=tf.stack([x, y, z]) print(a)执行结果如下:
tf.Tensor( [[1 4] [2 5] [3 6]], shape=(3, 2), dtype=int32)理解: 3个元素按照0轴进行堆叠,所以结果的tensor张量
0轴为3,由于原数据形状是2,所以结果的tensor张量1轴为2,即:结果tensor形状为(3,2)
测试代码
b=tf.stack([x, y, z], axis=1) print(b)执行结果如下:
tf.Tensor( [[1 2 3] [4 5 6]], shape=(2, 3), dtype=int32)理解: 3个元素按照1轴进行堆叠,所以结果的tensor张量
1轴为3,原数据形状是2,所以结果的tensor张量0轴为2,即:结果的tensor形状为(2,3)
二维数组
x = tf.constant([[1, 4, 7],[10, 13, 16]])
y = tf.constant([[2, 5, 8],[11, 14, 17]])
z = tf.constant([[3, 6, 9],[12, 15, 18]])
测试代码
a=tf.stack([x, y, z]) print(a)执行结果:
tf.Tensor( [[[ 1 4 7] [10 13 16]] [[ 2 5 8] [11 14 17]] [[ 3 6 9] [12 15 18]]], shape=(3, 2, 3), dtype=int32)理解: 3个tensor按照0轴进行堆叠,所以结果的tensor张量
0轴为3,原数据形状是(2,3),即:结果的tensor形状为(3,2,3)
测试代码
b=tf.stack([x, y, z],axis=1) print(b)执行结果如下:
tf.Tensor( [[[ 1 4 7] [ 2 5 8] [ 3 6 9]] [[10 13 16] [11 14 17] [12 15 18]]], shape=(2, 3, 3), dtype=int32)理解: 3个tensor按照1轴进行堆叠,所以结果的tensor张量
1轴为3,原数据形状是(2,3),即:结果的tensor形状为(2,3,3)
测试代码
c=tf.stack([x, y, z],axis=2) print(c)执行结果:
tf.Tensor( [[[ 1 2 3] [ 4 5 6] [ 7 8 9]] [[10 11 12] [13 14 15] [16 17 18]]], shape=(2, 3, 3), dtype=int32)理解: 3个tensor按照2轴进行堆叠,所以结果的tensor张量
2轴为3,原数据形状是(2,3),即:结果的tensor形状为(2,3,3)