Sample rows from tensor in every 3 rows in Python

Question:

How to sample the tensor in Python?
I want to sample a frame every 3 frames from videos, and the tensor shape will be [color, frames, height, width].
Thus, the sampling tensor shape will be [color, frames / 3, height, width]

Assume there is a tensor.size([3,300,10,10]).
After sampling rows every 3 rows in the second dimension, the tensor will be tensor.size([3,100,10,10])

Another example,
A tensor = [[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10]].
After sampling rows every 3 rows in the second dimension, the tensor will be [[1,4,7,10],[1,4,7,10],[1,4,7,10]]

Asked By: Alan Chuang

||

Answers:

Let N be the size of dimension you want to sample and you want to sample every kth row.

You can do (assuming you want to sample from the 1st dimension, and there are 4 dimensions),

new_tensor = tensor[:, torch.arange(0, N, k), : ,: ]

You may skip slicing the last two dimensions and the result won’t change.

new_tensor = tensor[:, torch.arange(0, N, k)]

More specifically for the 2D tensor in question, you can use this code.

tensor=torch.tensor([
             [1,2,3,4,5,6,7,8,9,10],
             [1,2,3,4,5,6,7,8,9,10],
             [1,2,3,4,5,6,7,8,9,10]
       ])
new_tensor=tensor[:, torch.arange(0,10,3)]
Answered By: Umang Gupta
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.