tf.concat, tf.stack和tf.unstack的用法

tf.concat, tf.stack和tf.unstack的用法
tf.concat相当于numpy中的np.concatenate函数,用于将两个张量在某一个维度(axis)合并起来,例如:

a = tf.constant([[1,2,3],[3,4,5]]) # shape (2,3)
b = tf.constant([[7,8,9],[10,11,12]]) # shape (2,3)
ab1 = tf.concat([a,b], axis=0) # shape(4,3)
ab2 = tf.concat([a,b], axis=1) # shape(2,6)

tf.stack其作用类似于tf.concat,都是拼接两个张量,而不同之处在于,tf.concat拼接的是除了拼接维度axis外其他维度的shape完全相同的张量,并且产生的张量的阶数不会发生变化,而tf.stack则会在新的张量阶上拼接,产生的张量的阶数将会增加,例如:

a = tf.constant([[1,2,3],[3,4,5]]) # shape (2,3)
b = tf.constant([[7,8,9],[10,11,12]]) # shape (2,3)
ab = tf.stack([a,b], axis=0) # shape (2,2,3)

改变参数axis为2,有:

import tensorflow as tf
a = tf.constant([[1,2,3],[3,4,5]]) # shape (2,3)
b = tf.constant([[7,8,9],[10,11,12]]) # shape (2,3)
ab = tf.stack([a,b], axis=2) # shape (2,3,2)

所以axis是决定其层叠(stack)张量的维度方向的。

而tf.unstack与tf.stack的操作相反,是将一个高阶数的张量在某个axis上分解为低阶数的张量,例如:

a = tf.constant([[1,2,3],[3,4,5]]) # shape (2,3)
b = tf.constant([[7,8,9],[10,11,12]]) # shape (2,3)
ab = tf.stack([a,b], axis=0) # shape (2,2,3)

a1 = tf.unstack(ab, axis=0)

其a1的输出为

[<tf.Tensor 'unstack_1:0' shape=(2, 3) dtype=int32>,
 <tf.Tensor 'unstack_1:1' shape=(2, 3) dtype=int32>]
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
TensorFlow 中的 `tf.stack` 和 `tf.concat` 都可以用于将多个张量拼接成一个张量,但它们的实现方式略有不同,具体如下: - `tf.concat`: 沿着一个指定的维度将多个张量拼接起来。例如,将两个形状为 `(3, 4)` 的张量沿着第一个维度拼接起来,得到一个形状为 `(6, 4)` 的张量。`tf.concat` 的实现方式是将多个张量在指定维度上直接拼接,因此要求各个输入张量在指定维度上大小相同。 - `tf.stack`: 沿着一个新的维度将多个张量堆叠起来。例如,将两个形状为 `(3, 4)` 的张量在第三个维度上堆叠起来,得到一个形状为 `(3, 4, 2)` 的张量。`tf.stack` 的实现方式是创建一个新的维度,并在这个维度上将各个输入张量堆叠起来,因此各个输入张量的大小可以不同,但在其它维度上的大小必须相同。 下面是具体的使用示例: ```python import tensorflow as tf # 定义两个张量 a = tf.constant([1, 2, 3]) b = tf.constant([4, 5, 6]) # 使用 tf.concat 将两个张量拼接成一个张量 c = tf.concat([a, b], axis=0) print(c) # 输出 [1 2 3 4 5 6] # 使用 tf.stack 将两个张量堆叠成一个张量 d = tf.stack([a, b], axis=1) print(d) # 输出 [[1 4] [2 5] [3 6]] ``` 在上面的例子中,我们首先定义了两个形状相同的张量 `a` 和 `b`。然后我们使用 `tf.concat` 将它们沿着第一个维度拼接起来,得到一个形状为 `(6,)` 的张量 `c`;接着使用 `tf.stack` 将它们在第二个维度上堆叠起来,得到一个形状为 `(3, 2)` 的张量 `d`。可以看到,`tf.concat` 和 `tf.stack` 的输出结果是不同的,这是因为它们的实现方式不同,使用时需要根据具体的需求选择合适的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值