簡體   English   中英

使用numpy生成n維中1和-1的所有組合?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM