【问题标题】:Efficient cosine distance calculation高效的余弦距离计算
【发布时间】:2014-08-21 03:16:18
【问题描述】:

我想根据矩阵的行计算向量的最近余弦邻居,并且一直在测试一些 Python 函数的性能。

def cos_loop_spatial(matrix, vector):
    """
    Calculating pairwise cosine distance using a common for loop with the numpy cosine function.
    """
    neighbors = []
    for row in range(matrix.shape[0]):
        neighbors.append(scipy.spatial.distance.cosine(vector, matrix[row,:]))
    return neighbors

def cos_loop(matrix, vector):
    """
    Calculating pairwise cosine distance using a common for loop with manually calculated cosine value.
    """
    neighbors = []
    for row in range(matrix.shape[0]):
        vector_norm = np.linalg.norm(vector)
        row_norm = np.linalg.norm(matrix[row,:])
        cos_val = vector.dot(matrix[row,:]) / (vector_norm * row_norm)
        neighbors.append(cos_val)
    return neighbors

def cos_matrix_multiplication(matrix, vector):
    """
    Calculating pairwise cosine distance using matrix vector multiplication.
    """
    dotted = matrix.dot(vector)
    matrix_norms = np.linalg.norm(matrix, axis=1)
    vector_norm = np.linalg.norm(vector)
    matrix_vector_norms = np.multiply(matrix_norms, vector_norm)
    neighbors = np.divide(dotted, matrix_vector_norms)
    return neighbors

cos_functions = [cos_loop_spatial, cos_loop, cos_matrix_multiplication]

# Test performance and plot the best results of each function
mat = np.random.randn(1000,1000)
vec = np.random.randn(1000)
cos_performance = {}
for func in cos_functions:
    func_performance = %timeit -o func(mat, vec)
    cos_performance[func.__name__] = func_performance.best

pd.Series(cos_performance).plot(kind='bar')

cos_matrix_multiplication 函数显然是其中最快的,但我想知道您是否有进一步提高矩阵向量余弦距离计算效率的建议。

【问题讨论】:

  • 既然您有工作代码并要求改进它,那么您在代码审查中可能会有更好的运气。
  • @wnnmaw 啊,我试试运气,谢谢!

标签: python numpy


【解决方案1】:

使用scipy.spatial.distance.cdist(mat, vec[np.newaxis,:], metric='cosine'),基本上计算两个向量集合的每对之间的成对距离,由两个输入矩阵的行表示。

【讨论】:

    猜你喜欢
    • 2020-06-06
    • 2016-11-29
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 2017-07-10
    • 2017-12-12
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多