[英]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?假设我有一个 2D numpy 数组,并想将其重塑为 3D,那么最好的方法是什么?
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
?但是,我怎样才能更有效地做到这一点,最好使用stride_tricks
?
Here's how I would do it with as_strided
:这是我将如何使用as_strided
:
window_length=3
strides = x.strides
new_len = (x.shape[0]-window_length+1)
out = as_strided(x,shape=(window_length, new_len, x.shape[1]),
strides=(strides[0],) + (strides[0], strides[1]))
Output:输出:
array([[[ 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]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.