【Pytorch】cat() 与 stack() 的区别

您所在的位置:网站首页 caterpillar和inchworm的区别 【Pytorch】cat() 与 stack() 的区别

【Pytorch】cat() 与 stack() 的区别

2024-04-02 13:21| 来源: 网络整理| 查看: 265

cat():

torch.cat(tensors, dim=0, *, out=None) → Tensor 连接给定维度中给定的张量序列seq。所有张量必须具有相同的形状(连接维度除外)或为空。 torch.cat()可以看作torch.split() 和 torch.chunk() 的逆运算。

参数:

tensors (sequence of Tensors) – 除了要进行cat的维度外,其余维度要和待拼接的tensor保持一致。dim (int, optional) – 连接张量的维度。

例子:

>>> x = torch.randn(2, 3) >>> x tensor([[ 0.6580, -1.0969, -0.4614], [-0.1034, -0.5790, 0.1497]]) >>> torch.cat((x, x, x), 0) tensor([[ 0.6580, -1.0969, -0.4614], [-0.1034, -0.5790, 0.1497], [ 0.6580, -1.0969, -0.4614], [-0.1034, -0.5790, 0.1497], [ 0.6580, -1.0969, -0.4614], [-0.1034, -0.5790, 0.1497]]) >>> torch.cat((x, x, x), 1) tensor([[ 0.6580, -1.0969, -0.4614, 0.6580, -1.0969, -0.4614, 0.6580, -1.0969, -0.4614], [-0.1034, -0.5790, 0.1497, -0.1034, -0.5790, 0.1497, -0.1034, -0.5790, 0.1497]]) stack():

torch.stack(tensors, dim=0, *, out=None) → Tensor 沿新维度连接一系列张量。 所有张量都需要具有相同的大小。

如对两个 (1, 2) 维的 tensor 在第 0 个维度上 stack,则会变为 (2, 1, 2) 的 tensor;在第 1 个维度上 stack,则会变为 (1, 2, 2) 的 tensor。

参数:

tensors (sequence of Tensors) – 要连接的tensordim (int, optional) – 进行连接的维度。

例子:

>>> x = torch.randn(2, 3) >>> x tensor([[ 1.4481, 0.9733, -0.2550], [-1.1247, 0.2517, 0.3983]]) >>> torch.stack((x,x),0) tensor([[[ 1.4481, 0.9733, -0.2550], [-1.1247, 0.2517, 0.3983]], [[ 1.4481, 0.9733, -0.2550], [-1.1247, 0.2517, 0.3983]]]) >>> torch.stack((x,x),1) tensor([[[ 1.4481, 0.9733, -0.2550], [ 1.4481, 0.9733, -0.2550]], [[-1.1247, 0.2517, 0.3983], [-1.1247, 0.2517, 0.3983]]]) 区别

torch.cat的使用方法,两个tensor除了要进行cat的维度外,其余维度必须一致,最终生成的tesnor的维度也没有变化。 从上边两个例子,可以看出对于torch.stack来说,会先将原始数据维度扩展一维,然后再按照维度进行拼接,具体拼接操作同torch.cat类似。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3