一行Tensor
import torch
x = torch.randint(4,(1, 4))
print(x)
a = x[None, :, :]
print(f'a.shape: {a.shape}')
b = x[:, None, :2]
print(b)
print(f'b.shape: {b.shape}')
c = x[:, None, 2:]
print(c)
print(f'c.shape: {c.shape}')
>>>
tensor([[0, 3, 2, 1]])
a.shape: torch.Size([1, 1, 4])
tensor([[[0, 3]]])
b.shape: torch.Size([1, 1, 2])
tensor([[[2, 1]]])
c.shape: torch.Size([1, 1, 2])
二维矩阵
import torch
x = torch.arange(12).reshape(3, 4)
print(x)
a = x[None, :, :]
print(f'a.shape: {a.shape}')
b = x[:, None, :2]
print(b)
print(f'b.shape: {b.shape}')
>>>
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
a.shape: torch.Size([1, 3, 4])
tensor([[[0, 1]],
[[4, 5]],
[[8, 9]]])
b.shape: torch.Size([3, 1, 2])