numpy 中 itertools.combinations 的 N 维版本

2023-11-21

我想实施itertools.combinations对于 numpy.基于这次讨论,我有一个适用于一维输入的函数:

def combs(a, r):
    """
    Return successive r-length combinations of elements in the array a.
    Should produce the same output as array(list(combinations(a, r))), but 
    faster.
    """
    a = asarray(a)
    dt = dtype([('', a.dtype)]*r)
    b = fromiter(combinations(a, r), dt)
    return b.view(a.dtype).reshape(-1, r)

输出是有意义的:

In [1]: list(combinations([1,2,3], 2))
Out[1]: [(1, 2), (1, 3), (2, 3)]

In [2]: array(list(combinations([1,2,3], 2)))
Out[2]: 
array([[1, 2],
       [1, 3],
       [2, 3]])

In [3]: combs([1,2,3], 2)
Out[3]: 
array([[1, 2],
       [1, 3],
       [2, 3]])

然而,如果我可以将其扩展到 N 维输入,那就更好了,其中额外的维度可以让您快速地一次执行多个调用。所以,从概念上讲,如果combs([1, 2, 3], 2)产生[1, 2], [1, 3], [2, 3], and combs([4, 5, 6], 2)产生[4, 5], [4, 6], [5, 6], then combs((1,2,3) and (4,5,6), 2)应该产生[1, 2], [1, 3], [2, 3] and [4, 5], [4, 6], [5, 6]其中“and”仅代表平行的行或列(以有意义的为准)。 (对于其他尺寸同样如此)

我不知道:

  1. 如何使维度以与其他函数的工作方式一致的逻辑方式工作(例如某些 numpy 函数如何具有axis=参数,默认为轴 0。所以轴 0 可能应该是我要组合的轴,而所有其他轴仅代表并行计算?)
  2. 如何让上面的代码与 ND 一起工作(现在我明白了ValueError: setting an array element with a sequence.)
  3. 有更好的方法吗dt = dtype([('', a.dtype)]*r)?

您可以使用itertools.combinations()创建索引数组,然后使用 NumPy 的奇特索引:

import numpy as np
from itertools import combinations, chain
from scipy.special import comb

def comb_index(n, k):
    count = comb(n, k, exact=True)
    index = np.fromiter(chain.from_iterable(combinations(range(n), k)), 
                        int, count=count*k)
    return index.reshape(-1, k)

data = np.array([[1,2,3,4,5],[10,11,12,13,14]])

idx = comb_index(5, 3)
print(data[:, idx])

output:

[[[ 1  2  3]
  [ 1  2  4]
  [ 1  2  5]
  [ 1  3  4]
  [ 1  3  5]
  [ 1  4  5]
  [ 2  3  4]
  [ 2  3  5]
  [ 2  4  5]
  [ 3  4  5]]

 [[10 11 12]
  [10 11 13]
  [10 11 14]
  [10 12 13]
  [10 12 14]
  [10 13 14]
  [11 12 13]
  [11 12 14]
  [11 13 14]
  [12 13 14]]]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

numpy 中 itertools.combinations 的 N 维版本 的相关文章

随机推荐