生成n维中的1和-1的所有组合与numpy?

时间:2017-02-21 14:21:19

标签: python numpy combinations

我需要一种方法来生成一个numpy数组,其中包含多个维度的[-1,1]的所有可能组合。

例如,如果我有2个维度,我会得到: [[1,1],[1,-1],[-1,1],[ - 1,-1]]

如果我有三个尺寸,我会得到: [[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的所有组合。

5 个答案:

答案 0 :(得分:2)

您可以使用itertools中的产品功能。

基本上,你可以通过重复2来获得所有组合。

print (list(itertools.product([1,-1], repeat=2)))
  

itertools.product(* iterables [,repeat])

     

输入迭代的笛卡尔积。

     

大致相当于生成器表达式中的嵌套for循环。

您可以在here

中阅读更多内容

答案 1 :(得分:1)

替换,

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

答案 2 :(得分:0)

您可能需要查看itertools。它是用于生成排序序列等的包。

import itertools as it

for element in it.combinations_with_replacement([1,-1],3):
  print element

答案 3 :(得分:0)

这是基于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]])

答案 4 :(得分:0)

您可以使用np.ix_。优点:您可以轻松地用您喜欢的任何内容替换-1,1(其他数字,其他数字,超过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))
相关问题