简体   繁体   English

从向量中执行逐元素减法

[英]Perform element-wise subtract from the vector

I need to calculate the sum of elementwise subtracts from the vector from the following equitation:我需要从以下等式计算向量中元素减去的总和:

sum(y(i) - y(j)) at i!=j

y is given as a numpy array y 以 numpy 数组的形式给出
One option is to iterate through the double loop:一种选择是遍历双循环:

dev = 0

for i in range(y.shape[0]):
   for j in range(y.shape[0]):
      if i == j:
         continue
      dev += y[i, j] - y[i, j]

That is definitely not the optimal solution.这绝对不是最佳解决方案。
How it can be optimized using vectorized operations with numpy vectors?如何使用带有 numpy 向量的向量化操作对其进行优化?

Say y is flat, eg假设y是平坦的,例如

>>> y = np.arange(10)
>>> y
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> y.shape
(10,)

You could compute the "cartesian differences" as follows您可以按如下方式计算“笛卡尔差异”


>>> m = np.abs(y[:, None] - y[None, :])
>>> m
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [1, 0, 1, 2, 3, 4, 5, 6, 7, 8],
       [2, 1, 0, 1, 2, 3, 4, 5, 6, 7],
       [3, 2, 1, 0, 1, 2, 3, 4, 5, 6],
       [4, 3, 2, 1, 0, 1, 2, 3, 4, 5],
       [5, 4, 3, 2, 1, 0, 1, 2, 3, 4],
       [6, 5, 4, 3, 2, 1, 0, 1, 2, 3],
       [7, 6, 5, 4, 3, 2, 1, 0, 1, 2],
       [8, 7, 6, 5, 4, 3, 2, 1, 0, 1],
       [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]])

and finally最后

>>> dev = m.sum()/2
>>> dev
165.0

using itertools combination :使用itertools combination

import itertools
sum([x2 - x1 for x1, x2 in itertools.combinations(y, 2)])

using np.subtract.outer使用np.subtract.outer

np.abs(np.subtract.outer(y,y)).sum()/2

Time Comparison:时间比较:

Method 1 (Using Itertools):方法1(使用Itertools):

Wall time: 18.9 s挂壁时间:18.9 秒

Method 2 (Using KeepAlive's cartesian differences):方法2(使用KeepAlive的笛卡尔差):

Wall time: 491 ms挂墙时间:491 毫秒

Method 3 (Using np.subtract.outer):方法 3(使用 np.subtract.outer):

Wall time: 467 ms挂墙时间:467 毫秒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM