【问题标题】:Fastest way to compute angle between 2D vectors计算二维向量之间角度的最快方法
【发布时间】:2025-12-30 16:10:16
【问题描述】:

我正在寻找有效的替代方法来计算二维向量之间的余弦角。您对此问题的见解将大有帮助。

问题陈述:

vectors 是一个存储向量的二维数组。 vectors 数组的形状是 (N, 2),其中 N 是向量的数量。 vectors[:, 0] 有 x 分量,vectors[:, 1] 有 y 分量。

我必须找到vectors 中所有向量之间的角度。比如vectors中有三个向量A、B、C,我需要找到A and BB and CA and C之间的夹角。

我已经实现了,想知道替代方法。

当前实施:

vectors = np.array([[1, 3], [2, 4], [3, 5]])

vec_x = vectors[:, 0]
vec_y = vectors[:, 1]

a1 = np.ones([vec_x.shape[0], vec_x.shape[0]]) * vec_x
a2 = np.ones([vec_x.shape[0], vec_x.shape[0]]) * vec_y
a1b1 = a1 * a1.T
a2b2 = a2 * a2.T
mask = np.triu_indices(a1b1.shape[0], 0) # We are interested in lower triangular matrix
a1b1[mask] = 0
a2b2[mask] = 0
numer = a1b1 + a2b2
denom = np.ones([vec_x.shape[0], vec_x.shape[0]]) * np.sqrt(np.square(a1) + np.square(a2))
denom = denom * denom.T
denom[mask] = 0
eps = 1e-7
dot_res = np.rad2deg(np.arccos(np.divide(numer, denom + eps)))
dot_res[mask] = 0
print(dot_res)

输出:

[[ 0.          0.          0.        ]
 [ 8.13010519  0.          0.        ]
 [12.52880911  4.39870821  0.        ]]

问题:

  1. 有没有其他更有效的方法?

  2. 我们可以通过某种方式提高当前版本的速度吗?

【问题讨论】:

    标签: python numpy vector numpy-ndarray


    【解决方案1】:

    使用scipy.spatial.distance.pdist:

    import numpy as np
    import scipy.spatial.distance
    
    vectors = np.array([[1, 3], [2, 4], [3, 5]])
    # Compute cosine distance
    dist = scipy.spatial.distance.pdist(vectors, 'cosine')
    # Compute angles
    angle = np.rad2deg(np.arccos(1 - dist))
    # Make it into a matrix
    angle_matrix = scipy.spatial.distance.squareform(angle)
    print(angle_matrix)
    # [[ 0.          8.13010235 12.52880771]
    #  [ 8.13010235  0.          4.39870535]
    #  [12.52880771  4.39870535  0.        ]]
    

    【讨论】: