TensorFlow 1.14中tensorflow.stack的axis=-1参数代表什么含义
TensorFlow 1.14 中
tf.stack 接口 axis=-1 参数含义说明 首先明确tf.stack的基础作用:该接口用于将多个形状完全一致的张量沿指定的新增维度进行堆叠,堆叠后输出的张量维度会比单个输入张量高1维。
axis=-1的具体含义
axis参数的取值范围为[-(R+1), R],其中R为单个输入张量的维度数,负值代表从张量的最后一个维度向前倒序计数:
axis=-1代表在输入张量的最后一个维度的后方插入新的堆叠轴,也就是堆叠操作发生在张量的最内层维度。- 该参数效果等价于取正索引
axis=R,R为输入张量的维度数。
代码示例(适配TensorFlow 1.14版本)
import tensorflow as tf # 定义2个形状均为(3, 4)的二维输入张量 a = tf.constant([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) b = tf.constant([[13,14,15,16], [17,18,19,20], [21,22,23,24]]) # 沿axis=-1执行堆叠 stacked_tensor = tf.stack([a, b], axis=-1) with tf.Session() as sess: res = sess.run(stacked_tensor) print("堆叠后张量形状:", res.shape) # 输出:堆叠后张量形状: (3, 4, 2)
从输出可以看到,两个形状为(3,4)的张量堆叠后得到形状为(3,4,2)的张量,最后一维长度为2,正好等于参与堆叠的输入张量数量。
内容的提问来源于stack exchange,提问作者James Arten
相关产品推荐
相关产品推荐

