Index a variable to be written

I have a problem about indexing variable in a forward pass. I have already known how to get a specified part to do some operation, but I don’t know how to write the result to the corresponding area and let gradients flow through the indexing part properly. For example:

input=Variable(torch.randn(2,3,5,6),requires_grad=True)
idx_w=Variable(torch.FloatTensor([2,3,4]),requires_grad=True).floor().detach()
idx_h=Variable(torch.FloatTensor([1,2]),requires_grad=True).floor().detach()
result=Variable(torch.zeros(input.size()),requires_grad=True)

output=input.index_select(dim=-1,index=idx_w.long()).index_select(dim=-2,index=idx_h.long())
output+=1

result[:,:,index_h,index_w]=output

But this way can cause an error that idx_h is a variable and can’t be converted to LongTensor.
Any advice would be appreciated !

I’m not sure I understand properly all the points, but here are some tips:

  • try using index_copy_ instead of advanced indexing (because you used two index_select, which is equivalent to input[:, :, :, idx_w.long()][:, :, idx_h.long(), :]
  • don’t forget to call .long() in your indexing variables