tensorflow stack unstack操作

本文介绍了 TensorFlow 中的 `stack` 和 `unstack` 函数,用于组合和拆分张量。`stack` 操作将多个秩为 R 的张量堆叠成秩为 R+1 的张量,而 `unstack` 则是其逆操作,将一个张量拆分为多个张量。示例代码展示了不同 `axis` 参数对结果的影响。
摘要由CSDN通过智能技术生成

1.stack操作

先看一下tensorflow中stack方法的函数签名

@tf_export("stack")
@dispatch.add_dispatch_support
def stack(values, axis=0, name="stack"):
  """Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor.

  See also `tf.concat`, `tf.tile`, `tf.repeat`.

  Packs the list of tensors in `values` into a tensor with rank one higher than
  each tensor in `values`, by packing them along the `axis` dimension.
  Given a list of length `N` of tensors of shape `(A, B, C)`;

  if `axis == 0` then the `output` tensor will have the shape `(N, A, B, C)`.
  if `axis == 1` then the `output` tensor will have the shape `(A, N, B, C)`.
  Etc.
  .......

stack操作是将一组秩为R的tensor叠成一个秩为R+1的tensor。

def stack_operation():
    x = tf.constant([1, 4])
    y = tf.constant([2, 5])
    z = tf.constant([3, 6])
    s1 = tf.stack([x, y, z])
    print(s1)
    s2 = tf.stack([x, y, z], axis=1)
    print(s2)

代码输出为:

tf.Tensor(
[[1 4]
 [2 5]
 [3 6]], shape=(3, 2), dtype=int32)
tf.Tensor(
[[1 2 3]
 [4 5 6]], shape=(2, 3), dtype=int32)

其中,axis指定为对哪个维度进行操作。如果axis=0,改变的则是最外层的维度,以此类推。

2.unstack

理解了上面的stack操作,unstack就好理解了,就是stack的逆操作。

def unstack_operation():
    s = tf.constant([[1, 2, 3], [4, 5, 6]])
    a = tf.unstack(s, axis=0)
    b = tf.unstack(s, axis=1)
    print(a)
    print(b)
[<tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 2, 3], dtype=int32)>, <tf.Tensor: shape=(3,), dtype=int32, numpy=array([4, 5, 6], dtype=int32)>]
[<tf.Tensor: shape=(2,), dtype=int32, numpy=array([1, 4], dtype=int32)>, <tf.Tensor: shape=(2,), dtype=int32, numpy=array([2, 5], dtype=int32)>, <tf.Tensor: shape=(2,), dtype=int32, numpy=array([3, 6], dtype=int32)>]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值