繁体   English   中英

有效地重塑 3D numpy 数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM