Pytorch学习笔记【5】---tensor的拼接和拆分

Pytorch学习笔记【5】—tensor的拼接和拆分

Pytorch笔记目录:点击进入

1.cat

把两个向量纵向拼接起来,并不会增加新的维度

# cat
a = torch.rand(4,32,8)
b = torch.rand(5,32,8)
print(torch.cat([a,b],dim=0).shape)
out:
torch.Size([9, 32, 8])
a1 =torch.rand(4,3,32,32)
a2 = torch.rand(5,3,32,32)
print(torch.cat([a1,a2],dim=0).shape)
a2 = torch.rand(4,1,32,32)
print(torch.cat([a1,a2],dim=1).shape)
out:
torch.Size([9, 3, 32, 32])
torch.Size([4, 4, 32, 32])

2.stack

把两个tensor横向连接起来,会增加一个新的维度

# stack create new dim
a1 = torch.rand(4,3,16,32)
a2 = torch.rand(4,3,16,32)
print(torch.stack([a1,a2],dim=2).shape)
out:
torch.Size([4, 3, 2, 16, 32])

3.根据长度来分割

# Split by len
a = torch.rand(32,8)
b = torch.rand(32,8)
c = torch.stack([a,b],dim=0)
print(c.shape)
aa,bb = c.split([1,1],dim=0)
print(aa.shape,bb.shape)
out:
torch.Size([2, 32, 8])
torch.Size([1, 32, 8]) torch.Size([1, 32, 8])

4.通过通道数来分割

# Split by num
aa,bb = c.chunk(2,dim=0)
print(aa.shape,bb.shape)
out:
torch.Size([1, 32, 8]) torch.Size([1, 32, 8])
原创文章 113 获赞 80 访问量 3万+

猜你喜欢

转载自blog.csdn.net/python_LC_nohtyp/article/details/106063673