我有一个z值的numpy 1D数组,我想计算所有条目组合之间的差,并将输出作为一个方矩阵。
I have a numpy 1D array of z values, and I want to calculate the difference between all combinations of the entries, with the output as a square matrix.
我知道如何使用cdist将其计算为所有点组合之间的距离,但这并没有给我以下符号:
I know how to calculate this as a distance between all combinations of the points using cdist, but that does not give me the sign:
例如,如果我的z向量为[1,5,8]
So for example if my z vector is [1,5,8]
import numpy as np from scipy.spatial.distance import cdist z=np.array([1, 5, 8]) z2=np.column_stack((z,np.zeros(3))) cdist(z2,z2)给我:
array([[0., 4., 7.], [4., 0., 3.], [7., 3., 0.]])但我想有迹象给我:
array([[0., 4., 7.], [-4., 0., 3.], [-7., -3., 0.]])我考虑过使用np.tril_indices翻转下三角形的符号来弄乱事物,但这是行不通的,因为我需要以一致的方式对两对进行区分(例如,如果我对两个或多个向量执行此操作,对是总是以相同的顺序进行比较),而通过翻转符号,我总是在右上方具有正差异,而在左下方则具有负差异。
I thought about fudging things by using np.tril_indices to flip the sign of the lower triangle, but this won't work, as I need the pairs to be differenced in a consistent way for my operation (i.e. if I perform this on two or more vectors, the pairs are always compared in the same order), whereas by flipping the sign I will always have positive differences in the upper right and negative in the lower left.
推荐答案In [29]: z = np.array([1, 5, 8]) In [30]: -np.subtract.outer(z, z) Out[30]: array([[ 0, 4, 7], [-4, 0, 3], [-7, -3, 0]])
(如果您不关心符号约定,请删除减号。)
(Drop the minus sign if you don't care about the sign convention.)