I believe it is a simple question, but I am stuck with it. I'm picking specific dimensions from a tensor like
input = x[i, :, 38:44]
Everything was fine until this point, but now I want to extract a different range of dimensions, such as:
38:44 then 46 to 48 then 50 to 54.
How can we do this?
CodePudding user response:
You send a list with the desired indices. For example, consider the following array:
import numpy as np
arr = np.array([[1,2], [2,3], [4,5], [6,7], [8,9]])
We can retrieve indices with the following way:
arr[[0,1,3], :]
Output:
array([[1, 2],
[2, 3],
[6, 7]])
Here I created a list of desired indices [0,1,3]
and send as retrieve the relevant dimensions.
So as for your question, you get declare whenever indices you want:
desired_indices = list(range(38,44)) list(range(46,48)) list(range(50,54))
my_input = x[i, :, desired_indices]
(I also change the "input" from the variable name as it will create a problem)
CodePudding user response:
The question of how to take multiple slices has come up often on SO.
If the slices are regular enough you may be able reshape the array, and take just one slice.
But more generally you have 2 options:
take the slices separately, and join them (
np.concatenate
)construct an advanced indexing array, and apply that. If the slices all have the same length you might make the array with
linspace
or a bit of broadcasted math. But if they differ, you have to concatenate a bunch ofarange
.
With x[i, :, arr]
where arr
is an array like np.array([38,39,50,60])
, there is a complicating factor that it mixes basic and advanced indexing. It is well known, at least among experienced numpy users, that this gives an unexpected shape, with the slice dimension(s) moved to the end.
x[i][:,arr]
is one way around this.