首页 文章详情

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

小黄用python | 2132 2019-12-22 23:20 0 0 0
UniSMS (合一短信)

d4e2d9bfe6a162b7fe30cf78f338c1f4.webp


77ae2ccb1a2878a01f6233fe347faefd.webp

前文传送门:

从零开始深度学习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)

47ace40aa0e21a2770dc1a18e4d09b59.webp

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

b1d119dbf955391719455d027aaa1693.webp

(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维

2a97414c76b2a47e7c9e3a29013c211e.webp

我们可以看到维度从拼接前的(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)

4da9e68b7b70c32f390a69f1a3abdd69.webp

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

4f57991d08f45c672522b0a58ca3ebe1.webp

张量的切分

(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)

d72fd2e05ee582c33e4e53ea4ae92acc.webp

可以看出后一个张量小于前一个张量的,前者第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个张量

5817b23fc5ec6cda6f2c60ba0334c4b8.webp

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个张量

27bf942e843f24f8281363e481ce8c6b.webp

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]


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

8e6338625136fde83e95366f03733fa5.webp你点的每个在看,我都认真当成了喜欢
good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter