gpt4 book ai didi

python - 从维数未知的 numpy 数组中提取超立方 block

转载 作者:太空宇宙 更新时间:2023-11-03 11:22:50 25 4
gpt4 key购买 nike

我有一些 python 代码,目前与二维数组硬连接如下:

import numpy as np
data = np.random.rand(5, 5)
width = 3

for y in range(0, data.shape[1] - W + 1):
for x in range(0, data.shape[0] - W + 1):
block = data[x:x+W, y:y+W]
# Do something with this block

现在,这是针对二维数组的硬编码,我想将其扩展到 3D 和 4D 数组。当然,我可以为其他维度编写更多函数,但我想知道是否有 python/numpy 技巧可以生成这些子 block ,而无需为多维数据复制此函数。

最佳答案

这是我对这个问题的看法。下面代码背后的想法是为每个数据切片找到“起始索引”。因此对于 5x5x5 数组的 4x4x4 子数组,起始索引将是 (0,0,0), (0,0,1), (0,1,0), (0,1,1) , (1,0,0), (1,0,1), (1,1,1),每个维度的切片长度为 4。

要获取子数组,您只需要遍历切片对象的不同元组并将它们传递给数组即可。

import numpy as np
from itertools import product

def iterslice(data_shape, width):
# check for invalid width
assert(all(sh>=width for sh in data_shape),
'all axes lengths must be at least equal to width')

# gather all allowed starting indices for the data shape
start_indices = [range(sh-width+1) for sh in data_shape]

# create tuples of all allowed starting indices
start_coords = product(*start_indices)

# iterate over tuples of slice objects that have the same dimension
# as data_shape, to be passed to the vector
for start_coord in start_coords:
yield tuple(slice(coord, coord+width) for coord in start_coord)

# create 5x5x5 array
arr = np.arange(0,5**3).reshape(5,5,5)

# create the data slice tuple iterator for 3x3x3 sub-arrays
data_slices = iterslice(arr.shape, 3)

# the sub-arrays are a list of 3x3x3 arrays, in this case
sub_arrays = [arr[ds] for ds in data_slices]

关于python - 从维数未知的 numpy 数组中提取超立方 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39331320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com