I want to slice a Tensor around a spatial location which is coming from another tensor. Is there any efficient way of achieving this? Below is an example of what I want. In this case I sliced a 3x3 tensor from the input tensor using the location from the location tensor.
input_tensor :
tensor([[[12, 30, 21, 32, 3, 38],
[ 8, 36, 20, 35, 16, 36],
[12, 31, 23, 30, 20, 20],
[33, 2, 10, 22, 31, 5],
[30, 13, 5, 2, 21, 7],
[34, 39, 32, 8, 6, 26]],
[[32, 5, 10, 19, 14, 29],
[ 3, 5, 27, 15, 2, 6],
[32, 6, 39, 15, 18, 37],
[19, 33, 19, 4, 29, 7],
[ 0, 32, 8, 28, 1, 5],
[24, 15, 39, 6, 39, 24]]])
location_tensor:
tensor([[4, 3],
[3, 1]])
Expected output,
tensor([[[10, 22, 31],
[ 5, 2, 21],
[32, 8, 6]],
[[32, 6, 39],
[19, 33, 19],
[ 0, 32, 8]]])
#####################
Code I used,
import torch
import torch.nn as nn
t1 = torch.randint(0, 40, (2, 6,6))
ix = torch.randint(1, 5, (2, 2))
print (t1)
print (ix)
t1_l = list(torch.unbind(t1))
ix_l = list(torch.unbind(ix))
t = torch.stack([t[0][t[1][0]-1:t[1][0]+2, t[1][1]-1:t[1][1]+2] for t in zip(t1_l, ix_l)])
print (t)