第一:
broading cast
a = torch.randn(4,3)
b = torch.rand(4,3)
c = a + b
c = torch.randn(1,3)
d = a+ c
结果:
a: tensor([[-0.9123, -0.3065, -0.5646],
[ 1.4327, 2.1845, -1.6093],
[ 0.9051, -1.2144, -1.6093],
[-0.6509, 0.7420, 1.0669]])
c tensor([[-1.8778, 1.3724, -1.6494]])
d的维度 torch.Size([4, 3])
d: tensor([[-2.7901, 1.0659, -2.2140],
[-0.4452, 3.5569, -3.2587],
[-0.9727, 0.1580, -3.2587],
[-2.5288, 2.1144, -0.5825]])
第二:
拼接1
a = torch.randn(5,32,48)
b = torch.randn(4,32,48)
c = torch.cat([a,b],dim=0)#在第0维度合并,如果a和b的尺寸除了在第一维度都相同的话,合并要将dim改为dim=1
print(c.shape)#torch.Size([9, 32, 48])
print(torch.cat([a,b]).shape)#默认拼接按照0维
拼接2
a = torch.randn(32,8)
b = torch.randn(32,8)
d = torch.stack([a,b],dim=2)
print(d.shape)#结果为:torch.Size([32, 8, 2])
第三:
拆分split
a = torch.randn(2,32,8)
b = a.split(1,dim=0)#第0个维度拆分
print(type(b))
拆分按数量区分
a = torch.randn(2,32,8)
b = a.chunk(2,dim=0)#第0个维度拆分
print(type(b))