从零开始深度学习Pytorch笔记(4)——张量的拼接与切分

浏览: 2911

前文传送门:

从零开始深度学习Pytorch笔记(1)——安装Pytorch

从零开始深度学习Pytorch笔记(2)——张量的创建(上)

从零开始深度学习Pytorch笔记(3)——张量的创建(下)

在该系列的上一篇:从零开始深度学习Pytorch笔记(3)——张量的创建(下我们介绍了更多Pytorch中的张量创建方式,本文研究张量的拼接与切分。

张量的拼接

import torch

(1) 使用torch.cat()拼接

将张量按维度dim进行拼接,不会扩张张量的维度

torch.cat(tensors, dim=0, out=None)

其中:

tensors:张量序列

dim:要拼接的维度

t = torch.ones((3,2))
t0 = torch.cat([t,t],dim=0)#在第0个维度上拼接
t1 = torch.cat([t,t],dim=1)#在第1个维度上拼接
print(t0,'\n\n',t1)

t2 = torch.cat([t,t,t],dim=0)
t2

(2) 使用torch.stack()拼接

在新创建的维度dim上进行拼接,会扩张张量的维度

torch.stack(tensors, dim=0, out=None)

参数:

tensors:张量序列

dim:要拼接的维度

t = torch.ones((3,2))
t1 = torch.stack([t,t],dim=2)#在新创建的维度上进行拼接
print(t1,t1.shape) #拼接完会从2维变成3维

我们可以看到维度从拼接前的(3,2)变成了(3,2,2),即在最后的维度上进行了拼接!

t = torch.ones((3,2))
t1 = torch.stack([t,t],dim=0)#在新创建的维度上进行拼接
#由于指定是第0维,会把原来的3,2往后移动一格,然后在新的第0维创建新维度进行拼接
print(t1,t1.shape)

t = torch.ones((3,2))
t1 = torch.stack([t,t,t],dim=0)#在新创建的维度上进行拼接
#由于是第0维,会把原来的3,2往后移动一格,然后在新的第0维创建新维度进行拼接
print(t1,t1.shape)

张量的切分

(1) 使用torch.chunk()切分

可以将张量按维度dim进行平均切分

return 张量列表

如果不能整除,最后一份张量小于其他张量

torch.chunk(input, chunks, dim=0)

参数:

input:要切分的张量

chunks:要切分的份数

dim:要切分的维度

a = torch.ones((5,2))
t = torch.chunk(a,dim=0,chunks=2)#在5这个维度切分,切分成2个张量
for idx, t_chunk in enumerate(t):
    print(idx,t_chunk,t_chunk.shape)

可以看出后一个张量小于前一个张量的,前者第0个维度上是3,后者是2。

(2) 使用torch.split()切分

将张量按维度dim进行切分

return:张量列表

torch.split(tensor, split_size_or_sections, dim=0)

参数:

tensor:要切分的张量

split_size_or_sections:为int时,表示每一份的长度;为list时,按list元素切分

dim:要切分的维度

a = torch.ones((5,2))
t = torch.split(a,2,dim=0)#指定了每个张量的长度为2
for idx, t_split in enumerate(t):
    print(idx,t_split,t_split.shape)#切出3个张量

a = torch.ones((5,2))
t = torch.split(a,[2,1,2],dim=0)#指定了每个张量的长度为列表中的大小【2,1,2】
for idx, t_split in enumerate(t):
    print(idx,t_split,t_split.shape)#切出3个张量

a = torch.ones((5,2))
t = torch.split(a,[2,1,1],dim=0)#list中求和不为长度则抛出异常
for idx, t_split in enumerate(t):
    print(idx,t_split,t_split.shape)#切出3个张量

RuntimeError:split_with_sizes expects split_sizes to sum exactly to 5 (input tensor's size at dimension 0), but got split_sizes=[2, 1, 1]

欢迎关注公众号学习之后的连载部分~

扫码下图关注我们不会让你失望!

image.png

推荐 0
本文由 ID王大伟 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册