簡體   English   中英

在Python中實現按元素的余弦相似度的最佳方法是什么?

[英]What is the best way to implement an element-wise cosine similarity in Python?

考慮到大型矩陣,下面的代碼效率很低。 有沒有更好的方法來實現呢?

我已經在網上搜索過此內容

import numpy as np

def cosine_similarity(x, y):
    return np.dot(x, y) / (np.sqrt(np.dot(x, x)) * np.sqrt(np.dot(y, y)))

def compare(a, b):

    c = np.zeros((a.shape[0], b.shape[0]))

    for i, ai in enumerate(a):
        for j, bj in enumerate(b):
            c[i, j] = cosine_similarity(ai, bj)

    return c

a = np.random.rand(100,2000)
b = np.random.rand(800,2000)

compare(a,b) # shape -> (100, 800)

如注釋中所述,如果要取兩個矩陣的乘積,則numpy已經對此進行了有效的實現,但對您來說可能太慢了(O(n ^ 3))。

import numpy as np

a=np.array([3,2,1])
b=np.array([1,2,3])
c=a.dot(b)
print(c) #output = 10

我在評論中看到您對向量之間的余弦距離感興趣。 對於余弦相似度,請考慮使用Scipy:

from scipy.spatial.distance import cosine

a=[1,0,1]
b=[0,1,0]
print(cosine(a,b)) #output = 1.0

這可能會更快滿足您的需求。 這是文檔

[個人編輯]

為了有效地計算余弦相似度,這是我寫的一個解決方案:

def compare(a, b):
    x = np.atleast_2d(np.sqrt(np.sum(a*a, axis=1))).T
    y = np.atleast_2d(np.sqrt(np.sum(b*b, axis=1))).T
    return a.dot(b.T) / x.dot(y.T)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM