假设我有一个2Dnumpy数组,并想要将其步进到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
发布于 2020-11-19 01:12:39
下面是我如何使用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]]])https://stackoverflow.com/questions/64897812
复制相似问题