Edit a subtensor of a 3D tensor

I have a tensor a of shape 3 x 4 x 5 and I want to edit the subtensor a[1, [0, 2, 3], :] and assign some value to it. How can I do that?

Currently, PyTorch only supports LongTensor indexing if it is the only argument. But I have two arguments for indexing

If it’s only a tensor (not a Variable for wich you want to keep the trace of operation in order to compute the gradient), you can use numpy, or do it by hand, because I don’t think it is implemented.

Otherwise (if you want to compute the gradient with respect to this assignment), I have no idea how to do it, since mathematically, an assignment is not differentiable at all.

If you dont want to assign, but to just get the values at the inedx targets, you can use index_select:

idx0 = torch.LongTensor([1])
idx1 = torch.LongTensor([0,2,3])
values = my_tensor.index_select(0,idx0).index_select(1,idx1)

on the master branch, this is now possible. you can indeed do:

x[1, [0, 2, 3], :] = y
1 Like

Will we have a function to do it with Variables in a “backwardable” way?

1 Like