所以我有矩陣 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)))
它確實創建了我,我希望輸出 的矩陣(256,4),但所有行都是相等的。這意味著我得到了 vector [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]]
輸出應該是矩陣可以形成的所有可能的陣列組合
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]]
我如何將這個程序推廣到更大的矩陣。
難道我做錯了什么?
謝謝!
uj5u.com熱心網友回復:
可以np.array與list( iterable )結合使用,尤其是在iterable為的情況下itertools.product(*A)。但是,這可以優化,因為您知道輸出陣列的形狀。
有很多方法可以執行,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 output
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盡管不包括在內,但它擊敗了大多數這些演算法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/396614.html
上一篇:numpy中陣列的對角線
