Sclicing torch Tensor

Hello, I need help
I have a torch tensor of size [1124823 x 13] and I want from the center " of the tensor to take five frames from the right and five frames from the left and concatenate them is there is any function do this?
" N.B."

Hi,

You can use things like t[base-5:base+5] where base is whatever you call the center of your Tensor :slight_smile:

sorry I can’t understand what is (t) and what is the base

t would be your Tensor of size [1124823 x 13].
And base is the index (as a python number) of the center. So something like base = t.size(0) // 2.

Do you mean this

base = feat.size(0)//2
x = feat[base-5: base:+5]

Yes if your tensor is called feat that will work.

Thanks albanD
But can I ask you if I want to go inside the center of each raw of the tensor take five elements from left and five from right

i = 0

j = 6

base = feat.szie(0)//2

for i in feat[i, j]:

x = feat[base - 5: base:+5]

i += 1

If you want to take form the second dimension, you can use the indexing syntax like: x = feat[:, base-5, base+5]. Or you can use the specialized function to get a subset: x = feat.narrow(1, base - 5, 10). The two will give exactly the same result.

Not excatly, I want to go form the center of each raw take five numbers from the left and five numbers from right

Rows are the second dimension for a 2D Tensor. So that should work.
Maybe you want to share an example with a given Tensor and which values you expect to get?

x = feat.narrow(1, base - 5, 10)

IndexError: Dimension out of range (expected to be in range of [-13, 12], but got 562406)

This is because the center of the second dimension is not the same as the one in the first dimension.

I am really confused about what you’re trying to do. I think an example of input/output that you want would help.

The tensor size [ 1124823 x 13 ]. So I want to slice each raw from its center and take 10 elements, 5 from the right and five from left. So I need to iterate through every raw.

What do you mean by “raw”? row?

If you have a Tensor of size [ 1124823 x 13 ], a single row is a 1D Tensor of size 13.
So you want to do: feat.narrow(1, feat.size(1)//2 -5, 10).

Yes, sorry for this typo it is raw.

But, Do I need a for loop to iterate for each raw

No, the operation above will give a Tensor of size [ 1124823 x 10 ] containing the result for every row.