5

寻找有关如何编写一个函数(或可以推荐一个已经存在的函数)的技巧,该函数计算数组中所有条目之间的差异,即数组diff()中所有条目组合的实现,而不仅仅是连续对。

这是我想要的一个例子:

# example array
a = [3, 2, 5, 1]

现在我们要应用一个函数,该函数将返回所有条目组合之间的差异。现在假设length(a) == 4这意味着组合的总数是,对于 N = 4;N*(N-1)*0.5 = 6(如果 a 的长度为 5,那么组合的总数将为 10,依此类推)。因此,该函数应为 vector 返回以下内容a

result = some_function(a)
print result
array([-1, 2, -2, 3, -1, -4])

因此,“函数”将类似于pdist但不是计算欧几里得距离,它应该简单地计算笛卡尔坐标沿一个轴(例如 z 轴)之间的差异,如果我们假设其中的条目a是坐标。可以注意到,我需要每个差异的符号来了解每个点位于轴的哪一侧。

谢谢。

4

2 回答 2

4

像这样的东西?

>>> import itertools as it
>>> a = [3, 2, 5, 1]
>>> [y - x for x, y in it.combinations(a, 2)]
[-1, 2, -2, 3, -1, -4]
于 2014-01-08T18:10:52.300 回答
1

所以我尝试了 wim 和 Joe 提出的方法(以及 Joe 和 wim 的综合建议),这就是我想出的:

import itertools as it
import numpy as np

a = np.random.randint(10, size=1000)

def cartesian_distance(x):
    return np.subtract.outer(x,x)[np.tril_indices(x.shape[0],k=-1)]

%timeit cartesian_distance(a)
%timeit [y - x for x, y in it.combinations(a, 2)]

10 loops, best of 3: 97.9 ms per loop
1 loops, best of 3: 333 ms per loop

对于较小的条目:

a = np.random.randint(10, size=10)

def cartesian_distance(x):
    return np.subtract.outer(x,x)[np.tril_indices(x.shape[0],k=-1)]

%timeit cartesian_distance(a)
%timeit [y - x for x, y in it.combinations(a, 2)]

10000 loops, best of 3: 78.6 µs per loop
10000 loops, best of 3: 40.1 µs per loop
于 2014-01-09T00:50:59.997 回答