tensorflow 中 tf.concat 和 tf.stack 使用

一、 tf.concat 

官方解释文档:https://tensorflow.google.cn/api_docs/python/tf/concat

函数原型:

tf.concat(
    values,                    # 要连接的张量
    axis,                      # 指定的连接维度
    name='concat'
)

官方解释:
values: A list of Tensor objects or a single Tensor.
axis: 0-D int32 Tensor. Dimension along which to concatenate. Must be in the range [-
       rank(values), rank(values)). As in Python, indexing for axis is 0-based. Positive         
       axis in the rage of [0, rank(values)) refers to axis-th dimension. And negative axis 
       refers to axis + rank(values)-th dimension.
name: A name for the operation (optional).

这是将张量按指定维度进行连接的函数。如下面实例所示:

t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
tf.concat([t1, t2], 0)  # [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
tf.concat([t1, t2], 1)  # [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]

# tensor t3 with shape [2, 3]
# tensor t4 with shape [2, 3]
tf.shape(tf.concat([t3, t4], 0))  # [4, 3]
tf.shape(tf.concat([t3, t4], 1))  # [2, 6]

二、tf.stack()

官方解释:https://tensorflow.google.cn/api_docs/python/tf/stack

函数原型:

tf.stack(
    values,
    axis=0,
    name='stack'
)


values: A list of Tensor objects with the same shape and type.
axis: An int. The axis to stack along. Defaults to the first dimension. Negative values 
      wrap around, so the valid range is [-(R+1), R+1).
name: A name for this operation (optional).

函数主要作用也是进行张量的连接,与上面那个函数的不同之处在于,这个函数支持在一个新的维度上进行连接。 如下面例子所示:

x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])
tf.stack([x, y, z])  # [[1, 4], [2, 5], [3, 6]] (Pack along first dim.)
tf.stack([x, y, z], axis=1)  # [[1, 2, 3], [4, 5, 6]]           # 注意,维度一在原来的x中是不存在的,也就是表明这个函数可以扩充维度

猜你喜欢

转载自blog.csdn.net/qq_37691909/article/details/85854939