【问题标题】:Compute pairwise differences between two vectors in numpy?在numpy中计算两个向量之间的成对差异?
【发布时间】:2021-01-22 18:59:59
【问题描述】:

我有两个向量,我想构建一个它们的成对差异矩阵。目前我这样做:

import numpy as np
a = np.array([1,2,3,4])
b = np.array([3,2,1])
M = a.reshape((-1,1)) - b.reshape((1,-1))

这当然有效,但我想知道这是否真的是预期的做事方式。该行的可读性次优;人们必须想一想reshapes 在做什么。这可以改进吗?是否有另一种“更清洁”的方式来实现相同的目标?

【问题讨论】:

  • 也许可以在Code Review 提出这个问题,因为它可能会危险地导致基于意见的问题。
  • 虽然可以使用outer进行减法,但如果更易读也可以使用M=a-b[:,None]
  • @Ehsan 这给出了M.T 而不是M

标签: python numpy


【解决方案1】:

使用numpyufunc (universal function) 功能,有一种无需手动重塑的有效方法。每个ufunc,包括np.subtract,都有一个名为outer的方法,它可以做你想做的事。 (documentation)

outer 将计算(在本例中为 np.subtract)应用于所有对。

>>> import numpy as np
>>> a = np.array([1,2,3,4])
>>> b = np.array([3,2,1])
>>> M = np.subtract.outer(a, b)
>>> M
array([[-2, -1,  0],
       [-1,  0,  1],
       [ 0,  1,  2],
       [ 1,  2,  3]])
>>>

让我们确认它是否符合您的预期结果。

>>> # This is how `M` was defined in the question:
>>> M = a.reshape((-1,1)) - b.reshape((1,-1))
>>> M
array([[-2, -1,  0],
       [-1,  0,  1],
       [ 0,  1,  2],
       [ 1,  2,  3]])

【讨论】:

  • 可爱,谢谢!我真的不知道这一点,但我怀疑应该有更好的解决方案。更具可读性。太好了!
猜你喜欢
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 2017-09-04
  • 1970-01-01
  • 2015-10-12
  • 1970-01-01
  • 2020-05-13
相关资源
最近更新 更多