How to do advanced indexing in PyTorch?

In Lua/Torch, I would do this:

input[{{}, {1, -2}, {1, -2}}]

But I can’t seem how to recreate in it in PyTorch.

I’ve tried different variations of brackets, like: input[((), (1, -2), (1, -2))]), but I keep getting the error:

IndexError: The advanced indexing objects could not be broadcast

input has a size of: (3L, 384L, 512L)

Edit:

I think this works:

input[:, (1, -2), (1, -2)]

Yes, It looks like the : slice in python is what you’re looking for :slight_smile:

@richard So would this:

self.x_diff = input[:, 1:-2, 1:-2] + input[:, 1:-2, 2:-1] 
self.y_diff = input[:, 1:-2, 1:-2] + input[:, 2:-1, 1:-2]

be the same as this in Lua/Torch:

  self.x_diff:copy(input[{{}, {1, -2}, {1, -2}}])
  self.x_diff:add(-1, input[{{}, {1, -2}, {2, -1}}])
  self.y_diff:copy(input[{{}, {1, -2}, {1, -2}}])
  self.y_diff:add(-1, input[{{}, {2, -1}, {1, -2}}])

Or am I doing it wrong?

I don’t think this is right:

input[:, 1:-2, 1:-2]

So I tried running:

import torch
import torch.nn as nn

input = torch.randn(3,64,64).cpu() #.cuda()
print(input.size()) # Works
test = input[:, [1,-2], [1,-2]]
print(test)

And I run into the following error:

(3L, 64L, 64L)
Traceback (most recent call last):
  File "t.py", line 6, in <module>
    test = input[:, [1,-2], [1,-2]]
RuntimeError: index out of range at /pytorch/torch/lib/TH/generic/THTensorMath.c:277

What am I doing wrong?

Well, that works for me, just not sure it does what you want. What is the expected output?