我的数据中有3D数组。我只是想在Python中以重叠间隔将2D数组2切2乘2。
这是2D的一个例子。
a = [1, 2, 3, 4;
5, 6, 7, 8]
此外,这是我在2×2切片后的预期。
[1, 2; [2, 3; [3, 4;
5, 6] 6, 7] 7, 8]
在3D中,
[[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]]
像这样,(也许不完全是......)
[1, 2 [2, 3
4, 5] 5, 6] ...
[1, 2 [2, 3
4, 5] 5, 6]
我认为,通过使用np.split,我可以切片数组,但没有重叠。请给我一些有用的提示。
你应该看看
numpy.ndarray.strides
和numpy.lib.stride_tricks
遍历数组时每个维度中的字节元组。数组(i[0], i[1], ..., i[n])
中元素a
的字节偏移量为:
offset = sum(np.array(i) * a.strides)
另见numpy documentation
遵循使用步幅的2D示例:
x = np.arange(20).reshape([4, 5])
>>> x
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
>>> from numpy.lib import stride_tricks
>>> stride_tricks.as_strided(x, shape=(3, 2, 5),
strides=(20, 20, 4))
...
array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9]],
[[ 5, 6, 7, 8, 9],
[ 10, 11, 12, 13, 14]],
[[ 10, 11, 12, 13, 14],
[ 15, 16, 17, 18, 19]]])
另请参阅此示例所在的Stackoverflow上的question,以增加您的理解。