Given an 2-dimensional tensor in numpy (or in pytorch), I can partially slice along all dimensions at once as follows:
>>> import numpy as np
>>> a = np.arange(2*3).reshape(2,3)
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> a[1:,1:]
array([[ 5, 6, 7],
[ 9, 10, 11]])
How can I achieve the same slicing pattern regardless of the number of dimensions in the tensor if I do not know the number of dimensions at implementation time? (i.e. I want a[1:]
if a
has only one dimension, a[1:,1:]
for two dimensions, a[1:,1:,1:]
for three dimensions, and so on)
It would be nice if I could do it in a single line of code like the following, but this is invalid:
a[(1:,) * len(a.shape)] # SyntaxError: invalid syntax
I am specifically interested in a solution that works for pytorch tensors (just substitute torch for numpy above and the example is the same), but I figure it is likely and best if the solution works for both numpy and pytorch.