gpt4 book ai didi

python - 计算numpy中两个向量之间的成对差异?

转载 作者:行者123 更新时间:2023-12-01 23:34:02 26 4
gpt4 key购买 nike

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

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))

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

最佳答案

有一种不需要您手动 reshape 的有效方法,使用 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]])

关于python - 计算numpy中两个向量之间的成对差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65851217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com