0

I have a PyTorch tensor b with the shape: torch.Size([10, 10, 51]). I want to select one element between the 10 possible elements in the dimension d=1 (middle one) using a numpy array: a = np.array([0,1,2,3,4,5,6,7,8,9]). this is just a random example.

I wanted to do: b[:,a,:] but that isn't working

4
  • So you expect back a tensor of shape (10, 51)? Commented Oct 4, 2021 at 16:51
  • @rkechols yes indeed Commented Oct 4, 2021 at 16:53
  • Your question is very unclear as to what you're expecting to get back. Please provide a small example of b tensor and what tensor you're expecting to get out. Commented Oct 4, 2021 at 19:47
  • it's okay, thanks for your help. I posted the answer Commented Oct 4, 2021 at 21:16

3 Answers 3

1

Your solution is likely torch.index_select (docs)

You'll have to turn a into a tensor first, though.

a_torch = torch.from_numpy(a)
answer = torch.index_select(b, 1, a_torch)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that is helpful
It didn't work. I got an array with the same size as ` b`
0

An indexing of b on the second axis using a should do:

>>> b = torch.rand(10, 10, 51)
>>> a = np.array([0,1,2,3,4,5,6,7,8,9])

>>> b[:,  a].shape
torch.Size([10, 10, 51])

3 Comments

I am trying to select only one element from the second dimension. In your result, the output still has an output shape of [10, 10, 51], while I want one such as [10, 51] @Ivan
I is not clear which element from the first axis you want to select, can you show a small example to illustrate the desired result?
I found the solution on the PyTorch forum. I will answer in a post. Thanks for the help
0

I have found the solution on the PyTorch forum: (https://discuss.pytorch.org/t/how-to-select-specific-vector-in-3d-tensor-beautifully/37724)

x = torch.tensor([[[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]],
                  [[11, 12, 13],
                   [14, 15, 16],
                   [17, 18, 19]]])

idx = torch.tensor([1, 2])
x[torch.arange(x.size(0)), idx]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.