import torch
import numpy as np
维度变换
a = torch.randint(1,10,[4,1,3,6])
a.reshape(-1,3,6)
tensor([[[6, 1, 8, 2, 3, 8],
[1, 7, 6, 9, 2, 7],
[1, 6, 2, 5, 7, 6]],
[[9, 4, 3, 9, 4, 2],
[4, 6, 8, 7, 7, 1],
[1, 3, 9, 7, 1, 8]],
[[6, 4, 5, 3, 6, 4],
[7, 9, 7, 1, 2, 1],
[1, 5, 7, 6, 5, 4]],
[[5, 6, 4, 2, 1, 6],
[9, 5, 4, 9, 3, 8],
[9, 1, 2, 4, 5, 8]]])
a = torch.randint(1,10,[3,4])
a
tensor([[6, 6, 9, 7],
[6, 5, 1, 5],
[6, 3, 8, 9]])
a.unsqueeze(0)
tensor([[[6, 6, 9, 7],
[6, 5, 1, 5],
[6, 3, 8, 9]]])
a.unsqueeze(1)
tensor([[[6, 6, 9, 7]],
[[6, 5, 1, 5]],
[[6, 3, 8, 9]]])
a.unsqueeze(2)
tensor([[[6],
[6],
[9],
[7]],
[[6],
[5],
[1],
[5]],
[[6],
[3],
[8],
[9]]])
a.unsqueeze(-1).shape
torch.Size([3, 4, 1])
a.unsqueeze(-3).shape
torch.Size([1, 3, 4])
b=a.reshape(2,1,2,3)
print(b.shape)
b
torch.Size([2, 1, 2, 3])
tensor([[[[6, 6, 9],
[7, 6, 5]]],
[[[1, 5, 6],
[3, 8, 9]]]])
print(b.squeeze())
print(b.squeeze().shape)
tensor([[[6, 6, 9],
[7, 6, 5]],
[[1, 5, 6],
[3, 8, 9]]])
torch.Size([2, 2, 3])
b.squeeze(0).shape
torch.Size([2, 1, 2, 3])
b.squeeze(1).shape
torch.Size([2, 2, 3])
c = a.reshape(1,1,6,2,1)
c.squeeze(-5).shape
torch.Size([1, 6, 2, 1])
c.squeeze(4).shape
torch.Size([1, 1, 6, 2])
a = torch.randint(1,10,[2,4,5])
b = torch.randint(1,10,[2,1,1])
b
tensor([[[5]],
[[1]]])
b.expand(2,4,5)
tensor([[[5, 5, 5, 5, 5],
[5, 5, 5, 5, 5],
[5, 5, 5, 5, 5],
[5, 5, 5, 5, 5]],
[[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]]])
b.expand(2,-1,3)
tensor([[[5, 5, 5]],
[[1, 1, 1]]])
b.repeat(2,1,3)
tensor([[[5, 5, 5]],
[[1, 1, 1]],
[[5, 5, 5]],
[[1, 1, 1]]])
a = torch.arange(24).reshape(2,3,4)
a.transpose(1,0).contiguous().reshape(2,3,4)
tensor([[[ 0, 1, 2, 3],
[12, 13, 14, 15],
[ 4, 5, 6, 7]],
[[16, 17, 18, 19],
[ 8, 9, 10, 11],
[20, 21, 22, 23]]])
-
- 填1,0或者0,1 都可以 原来的Xijk 变成了Xjik
a.permute(2,1,0).shape
torch.Size([4, 3, 2])
a.permute(1,2,0).shape
torch.Size([3, 4, 2])