[英]efficiently reshaping 3D numpy array
假設我有一個 2D numpy 數組,並想將其重塑為 3D,那么最好的方法是什么?
小例子:
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)
這將正確返回預期結果:
[[ 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]]]
但是,我怎樣才能更有效地做到這一點,最好使用stride_tricks
?
這是我將如何使用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]))
輸出:
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.