1.切片
import torch
b=torch.tensor([[[1, 2, 3,4]]])
print(b)
a=b[:,:,0:4:2].shape
print(a)
print(b[:,:,0:4:2])
print(b)
结果:tensor([[[1, 2, 3, 4]]])
torch.Size([1, 1, 2])
tensor([[[1, 3]]])
tensor([[[1, 2, 3, 4]]])
2.维度变幻
2.1view/reshape
import torch
b=torch.rand(1,1,3,3)
print(b)
a=b.view(1,1*3*3)
print(a)
c=b.view(1*1*3,3)
print(c)
结果:tensor([[[[0.5734, 0.3008, 0.0772],
[0.8198, 0.1803, 0.3937],
[0.0340, 0.9622, 0.0150]]]])
tensor([[0.5734, 0.3008, 0.0772, 0.8198, 0.1803, 0.3937, 0.0340, 0.9622, 0.0150]])
tensor([[0.5734, 0.3008, 0.0772],
[0.8198, 0.1803, 0.3937],
[0.0340, 0.9622, 0.0150]])
2.2Squeeze压缩维度,自动化,只能压缩1/unsqueeze展开维度
import torch
b=torch.tensor([1,1,3,3])
print(b)
print(b.shape)
a=b.unsqueeze(0)
print(a)
print(a.shape)
c=b.unsqueeze(-1)
print(c)
print(c.shape)
结果:tensor([1, 1, 3, 3])
torch.Size([4])
tensor([[1, 1, 3, 3]])
torch.Size([1, 4])
tensor([[1],
[1],
[3],
[3]])
torch.Size([4, 1])
2.3Transpose/t/permute
2.3.1 t二维
import torch
b=torch.randn(2,3)
print(b)
a=b.t()
print(a)
结果:
tensor([[ 6.8482e-01, 1.0790e+00, -4.5453e-04],
[-2.3182e+00, 7.3845e-01, 1.0354e+00]])
tensor([[ 6.8482e-01, -2.3182e+00],
[ 1.0790e+00, 7.3845e-01],
[-4.5453e-04, 1.0354e+00]])
2.3.2 Transpose
import torch
b=torch.randn(4,2,3,8)
a1=b.transpose(1,3).contiguous().view(4,2*3*8).view(4,2,3,8)
a2=b.transpose(1,3).contiguous().view(4,2*3*8).view(4,8,3,2).transpose(1,3)
#a2=b.transpose(1,3).contiguous().view(4,8,3,2).transpose(1,3)#same
print(torch.all(torch.eq(b,a1)))
print(torch.all(torch.eq(b,a2)))
结果:
tensor(0, dtype=torch.uint8)
tensor(1, dtype=torch.uint8)
2.4Expand/repeat建议少用
import torch
b=torch.rand(1,3,14,14)
print(b.shape)
a=b.expand(4,3,14,14)
print(a.shape)
结果:
torch.Size([1, 3, 14, 14])
torch.Size([4, 3, 14, 14])