簡體   English   中英

二維數組的所有元素的所有組合

[英]All combinations of all elements of a 2D array

所以我有矩陣A

A = [[0,0,1,-1] 
     [0,0,1,-1]
     [0,0,1,-1]
     [0,0,1,-1]]

我想擁有這些元素的所有可能組合。 這意味着行也可以在它們和列之間更改。 在這種情況下,我預計有4^4 = 256種可能性。 我努力了:

combs = np.array(list(itertools.product(*A)))

它確實創造了我,我希望 output 的矩陣為(256,4) ,但所有行都是相等的。 這意味着我得到向量[0,0,1,-1] 256次。

這是一個例子:

output = [[0,0,0,0]
          [0,0,0,1]
          [0,0,1,1]
          [0,1,1,1]
          [1,1,1,1]
          [-1,1,1,-1]
          [-1,-1,-1,-1]
             ....
          [0,-1,0,-1]

另一個例子,如果

A = [[1,2,3] 
     [4,5,6]
     [7,8,9]]

output應該是矩陣可以形成的arrays的所有可能組合

Combs =[[1,1,1] 
        [1,1,2]
        [1,1,3]
        [1,1,...9]
        [2,1,1]
        [2,2,1]
        [1,2,1]

另一個例子是:我有矢量圖層

layers = [1,2,3,4,5]

然后我有矢量角

angle = [0,90,45,-45]

每一層都可以有一個角度,所以我創建了一個矩陣 A

A = [[0,90,45,-45]
     [0,90,45,-45]
     [0,90,45,-45]
     [0,90,45,-45]
     [0,90,45,-45]]

太好了,但現在我想知道圖層可以具有的所有可能組合。 例如,第 1 層的角度可以為 0º,第 2 層的角度可以為 90º,第 3 層的角度可以為 0º,第 4 層的角度可以為 45º,第 5 層的角度可以為 0º。 這將創建數組

Comb = [0,90,0,45,0]

所以所有的組合都在一個矩陣中

Comb = [[0,0,0,0,0]
        [0,0,0,0,90]
        [0,0,0,90,90]
        [0,0,90,90,90] 
        [0,90,90,90,90] 
        [90,90,90,90,90] 
             ...
        [0,45,45,45,45]
        [0,45,90,-45,90]]

我如何將這個過程推廣到更大的矩陣。

難道我做錯了什么?

謝謝!

可以將np.arraylistiterable )結合使用,尤其是在iterableitertools.product(*A)的情況下。 但是,這可以優化,因為您知道 output 的陣列形狀。

有很多方法可以執行product ,所以我將列出我的清單:

笛卡爾積的方法

import itertools
import numpy as np

def numpy_product_itertools(arr):
    return np.array(list(itertools.product(*arr)))

def numpy_product_fromiter(arr):
    dt = np.dtype([('', np.intp)]*len(arr)) #or np.dtype(','.join('i'*len(arr)))
    indices = np.fromiter(itertools.product(*arr), dt)
    return indices.view(np.intp).reshape(-1, len(arr))

def numpy_product_meshgrid(arr):
    return np.stack(np.meshgrid(*arr), axis=-1).reshape(-1, len(arr))

def numpy_product_broadcast(arr): #a little bit different type of input
    items = [np.array(item) for item in arr]
    idx = np.where(np.eye(len(arr)), Ellipsis, None)
    out = [x[tuple(i)] for x,i in zip(items, idx)]
    return list(np.broadcast(*out))

使用示例

A = [[1,2,3], [4,5], [7]]
numpy_product_itertools(A)
numpy_product_fromiter(A)
numpy_product_meshgrid(A)
numpy_product_broadcast(A)

性能比較

import benchit
benchit.setparams(rep=1)
%matplotlib inline
sizes = [3,4,5,6,7]
N = sizes[-1]
arr = [np.arange(0,100,10).tolist()] * N
fns = [numpy_product_itertools, numpy_product_fromiter, numpy_product_meshgrid, numpy_product_broadcast]
in_ = {s: (arr[:s],) for s in sizes}
t = benchit.timings(fns, in_, multivar=True, input_name='Cartesian product of N arrays of length=10')
t.plot(logx=False, figsize=(12, 6), fontsize=14)

在此處輸入圖像描述

請注意, numba擊敗了大多數這些算法,盡管它不包括在內。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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