2

say I have a sequence s and I'd like to select n random sub sequences from it each with length l and store in a matrix. Is there a more numpy way of doing that than

s = np.arange(0, 1000)
n = 5
l = 10
i = np.random.randint(0, len(s)-10, 5)
ss = np.array([s[x:x+l] for x in i])

1 Answer 1

3

We can leverage np.lib.stride_tricks.as_strided based scikit-image's view_as_windows for efficient patch extraction, like so -

from skimage.util.shape import view_as_windows

# Get sliding windows (these are simply views)
w = view_as_windows(s, l)

# Index with indices, i for desired output
out = w[i]

Related :

NumPy Fancy Indexing - Crop different ROIs from different channels

Take N first values from every row in NumPy matrix that fulfill condition

Selecting Random Windows from Multidimensional Numpy Array Rows

Sign up to request clarification or add additional context in comments.

1 Comment

superb, solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.