efficiently reshaping 3D numpy array

assuming I have a 2D numpy array and want to reshape it with strides into 3D, what would be the best way to do that?

little example:

def find_ngrams(input_list, n):
    return np.array(list(zip(*[input_list[i:] for i in range(n)])))

x = np.array(range(15))
x = x.reshape((5,3))
print(x)
print(x.shape)

res = find_ngrams(x, 3)
print(res.shape)
print(res)

This returns the expected result correctly:

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]
 [12 13 14]]
(5, 3)
(3, 3, 3)
[[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]]

 [[ 3  4  5]
  [ 6  7  8]
  [ 9 10 11]]

 [[ 6  7  8]
  [ 9 10 11]
  [12 13 14]]]

However, how can I do this more efficiently, preferably using stride_tricks?



Read more here: https://stackoverflow.com/questions/64897812/efficiently-reshaping-3d-numpy-array

Content Attribution

This content was originally published by user3320142 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: