这是一个没有生成所有组合的矢量化方法 –
def unique_combs(A, N):
# A : 2D Input array with each row representing one group
# N : No. of combinations needed
m,n = A.shape
dec_idx = np.random.choice(2**m,N,replace=False)
idx = ((dec_idx[:,None] & (1 << np.arange(m)))!=0).astype(int)
return A[np.arange(m),idx]
请注意,这假设我们处理的是每组相同数量的元素.
说明
为了给它一些解释,让我们说这些组存储在一个二维数组中 –
In [44]: A
Out[44]:
array([[4, 2],
[3, 5],
[8, 6]])
我们每组有两个元素.假设我们正在寻找4种独特的组合组合:N = 4.要从这三组中的每一组中选择两个数字,我们总共有8种独特的组合.
让我们使用np.random.choice(8,N,replace = False)在8的间隔中生成N个唯一数字 –
In [86]: dec_idx = np.random.choice(8,N,replace=False)
In [87]: dec_idx
Out[87]: array([2, 3, 7, 0])
然后,将它们转换为二进制等价物,稍后我们需要将它们索引到A的每一行 –
In [88]: idx = ((dec_idx[:,None] & (1 <&l