问题:我想创建一个5维的numpy矩阵,每列的值限制在一个范围内。对于这个问题,我在网上找不到任何解决方案。
我正在尝试生成表单中的规则列表
Rule: (wordIndex, row, col, dh, dv) 每列具有范围( (0-7)、(0,11)、(0,11)、(-1,1)、(-1,1) )中的值。我想生成所有可能的组合。
我可以很容易地使用五个循环,一个循环在另一个循环中。
m, n = 12, 12
rules =[]
for wordIndex in range(0, 15):
for row in range(0,m):
for col in range(0,n):
for dh in range(-1,2):
for dv in range(-1,2):
rules.append([wordIndex, row, col, dh, dv])但是这种方法需要大量的时间,我想知道是否有更好的、矢量化的方法来使用numpy来解决这个问题。
我尝试了以下方法,但似乎都不起作用:
rules = np.mgrid[words[0]:words[-1], 0:11, 0:11, -1:1, -1:1]
rules = np.rollaxis(words,0,4)
rules = rules.reshape((len(words)*11*11*3*3, 5))另一种失败的方法:
values = list(itertools.product(len(wordsGiven()), range(11), range(11), range(-1,1), range(-1,1)))我也尝试过np.arange(),但似乎不知道如何对多维数组使用if。
发布于 2020-04-26 11:26:28
我认为应该有更好的方法来解决它。但以防万一你找不到它,这里有一个基于数组的方法:
shape = (8-0, 12-0, 12-0, 2-(-1), 2-(-1))
a = np.zeros(shape)
#create array of indices
a = np.argwhere(a==0).reshape(*shape, len(shape))
#correct the ranges that does not start from 0, here 4th and 5th elements (dh and dv) reduced by -1 (starting range).
#You can adjust this for any other ranges and elements easily.
a[:,:,:,:,:,3:5] -= 1的前几个元素:
[[[[[[ 0 0 0 -1 -1]
[ 0 0 0 -1 0]
[ 0 0 0 -1 1]]
[[ 0 0 0 0 -1]
[ 0 0 0 0 0]
[ 0 0 0 0 1]]
[[ 0 0 0 1 -1]
[ 0 0 0 1 0]
[ 0 0 0 1 1]]]
[[[ 0 0 1 -1 -1]
[ 0 0 1 -1 0]
[ 0 0 1 -1 1]]
[[ 0 0 1 0 -1]
[ 0 0 1 0 0]
[ 0 0 1 0 1]]
[[ 0 0 1 1 -1]
[ 0 0 1 1 0]
[ 0 0 1 1 1]]]
[[[ 0 0 2 -1 -1]
[ 0 0 2 -1 0]
[ 0 0 2 -1 1]]
[[ 0 0 2 0 -1]
[ 0 0 2 0 0]
[ 0 0 2 0 1]]
[[ 0 0 2 1 -1]
[ 0 0 2 1 0]
[ 0 0 2 1 1]]]
...https://stackoverflow.com/questions/61435156
复制相似问题