当前位置: 代码迷 >> 综合 >> tensorflow 中 tf.concat 和 tf.stack 使用
  详细解决方案

tensorflow 中 tf.concat 和 tf.stack 使用

热度:41   发布时间:2023-11-22 04:00:52.0

一、 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中是不存在的,也就是表明这个函数可以扩充维度

 

  相关解决方案