DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on • Edited on

select in PyTorch

Buy Me a Coffee

*Memos:

select() can get the 0D or more D view tensor of the zero or more elements selected with an index, removing one dimension from the 0D or more D tensor of zero or more elements as shown below:

*Memos:

  • select() can be used with torch or a tensor.
  • The 1st argument(input) with torch or using a tensor(Required-Type:tensor of int, float, complex or bool). *It must be the 0D or more D tensor of zero or more elements.
  • The 2nd argument with torch or the 1st argument with a tensor is dim(Required-Type:int).
  • The 3rd argument with torch or the 2nd argument with a tensor is index(Required-Type:int).
import torch

my_tensor = torch.tensor([8, -3, 0, 1, 5, -2, -1, 4])

torch.select(input=my_tensor, dim=0, index=1)
my_tensor.select(dim=0, index=1)
torch.select(input=my_tensor, dim=0, index=-7)
torch.select(input=my_tensor, dim=-1, index=1)
torch.select(input=my_tensor, dim=-1, index=-7)
# tensor(-3)

torch.select(input=my_tensor, dim=0, index=4)
torch.select(input=my_tensor, dim=0, index=-4)
torch.select(input=my_tensor, dim=-1, index=4)
torch.select(input=my_tensor, dim=-1, index=-4)
# tensor(5)

my_tensor = torch.tensor([[8, -3, 0, 1],
                          [5, -2, -1, 4]])
torch.select(input=my_tensor, dim=0, index=1)
torch.select(input=my_tensor, dim=0, index=-1)
torch.select(input=my_tensor, dim=-2, index=1)
torch.select(input=my_tensor, dim=-2, index=-1)
# tensor([5, -2, -1, 4])

torch.select(input=my_tensor, dim=1, index=3)
torch.select(input=my_tensor, dim=1, index=-1)
torch.select(input=my_tensor, dim=-1, index=3)
torch.select(input=my_tensor, dim=-1, index=-1)
# tensor([1, 4])

my_tensor = torch.tensor([[[8, -3], [0, 1]],
                          [[5, -2], [-1, 4]]])
torch.select(input=my_tensor, dim=2, index=1)
torch.select(input=my_tensor, dim=2, index=-1)
torch.select(input=my_tensor, dim=-1, index=1)
torch.select(input=my_tensor, dim=-1, index=-1)
# tensor([[-3, 1],
#         [-2, 4]])

my_tensor = torch.tensor([[[8., -3.], [0., 1.]],
                          [[5., -2.], [-1., 4.]]])
torch.select(input=my_tensor, dim=2, index=1)
# tensor([[-3., 1.],
#         [-2., 4.]])

my_tensor = torch.tensor([[[8.+0.j, -3.+0.j], [0.+0.j, 1.+0.j]],
                          [[5.+0.j, -2.+0.j], [-1.+0.j, 4.+0.j]]])
torch.select(input=my_tensor, dim=2, index=1)
# tensor([[-3.+0.j, 1.+0.j],
#         [-2.+0.j, 4.+0.j]])

my_tensor = torch.tensor([[[True, False], [True, False]],
                          [[False, True], [False, True]]])
torch.select(input=my_tensor, dim=2, index=1)
# tensor([[False, False],
#         [True, True]])
Enter fullscreen mode Exit fullscreen mode

Top comments (0)