[英]Generating all combinations of 1 and -1 in n Dimensions with numpy?
我需要一种在给定尺寸的情况下使用[-1,1]的所有可能组合生成numpy数组的方法。
例如,如果我有2个维度,我将得到:[[1,1],[1,-1],[-1,1],[-1,-1]]
如果我有3个维度,我会得到:[[1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],[-1, 1,1],[-1,1,-1],[-1,-1,1],[-1,-1,-1]],
我已经尝试过这样的事情:
import numpy as np
def permgrid(n):
inds = np.indices((2,) * n)
return inds.reshape(n, -1).T
但这只会返回0和1的所有组合。
您可以使用itertools中的product函数。
基本上,您会得到所有重复为2的组合。
print (list(itertools.product([1,-1], repeat=2)))
itertools.product(* iterables [,重复])
输入可迭代项的笛卡尔积。
大致等效于生成器表达式中的嵌套for循环。
你可以在这里阅读更多
要么替换,
def permgrid(n):
inds = np.indices((2,) * n)
out = inds.reshape(n, -1).T
return np.where(out==0, -np.ones_like(out), out)
或用数学来做:
def permgrid(n):
inds = np.indices((2,) * n)
return inds.reshape(n, -1).T*2-1
您可能想看看itertools
。 它是用于生成排序序列等的程序包。
import itertools as it
for element in it.combinations_with_replacement([1,-1],3):
print element
这是NumPy's broadcasting
基于NumPy's broadcasting
的方法-
def broadcasting_typecast(n):
return -2*((np.arange(2**n)[:,None] & (1 << np.arange(n-1,-1,-1))) != 0)+1
样品运行-
In [231]: n = 2
In [232]: broadcasting_typecast(n)
Out[232]:
array([[ 1, 1],
[ 1, -1],
[-1, 1],
[-1, -1]])
In [233]: n = 3
In [234]: broadcasting_typecast(n)
Out[234]:
array([[ 1, 1, 1],
[ 1, 1, -1],
[ 1, -1, 1],
[ 1, -1, -1],
[-1, 1, 1],
[-1, 1, -1],
[-1, -1, 1],
[-1, -1, -1]])
您可以使用np.ix_
。 优点:您可以轻松地将-1,1
替换为所需的数字(其他数字,其他dtype,大于2等)
>>> n = 3
>>> out = np.empty(n*(2,)+(n,), dtype=int)
>>> for j, sl in enumerate(np.ix_(*(n*((-1,1),)))):
... out[..., j] = sl
...
>>> out
array([[[[-1, -1, -1],
[-1, -1, 1]],
[[-1, 1, -1],
[-1, 1, 1]]],
[[[ 1, -1, -1],
[ 1, -1, 1]],
[[ 1, 1, -1],
[ 1, 1, 1]]]])
可选地:
flat_out = np.reshape(out, (-1, n))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.