[英]create a function to compute all pairwise cosine similarity of the row vectors in a 2-D matrix using only numpy
例如,給定矩陣
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
它應該返回
array([[1. , 0.91465912, 0.87845859],
[0.91465912, 1. , 0.99663684],
[0.87845859, 0.99663684, 1. ]])
其中結果的(i, j)
項是行向量arr[i]
和行向量arr[j]
之間的余弦相似度: cos_sim[i, j] == CosSim(arr[i], arr[j])
。
這個 function 應該返回一個 np.ndarray 形狀 (arr.shape[0], arr.shape[0])
嘗試:
from scipy.spatial.distance import cdist
1 - cdist(a, a, metric='cosine')
Output:
array([[1. , 0.91465912, 0.87845859],
[0.91465912, 1. , 0.99663684],
[0.87845859, 0.99663684, 1. ]])
a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
p = a / np.linalg.norm(a, 2, axis=1).reshape(-1,1)
p
array([[0. , 0.18257419, 0.36514837, 0.54772256, 0.73029674],
[0.31311215, 0.37573457, 0.438357 , 0.50097943, 0.56360186],
[0.37011661, 0.40712827, 0.44413993, 0.48115159, 0.51816325]])
請注意,范數必須逐行計算。 所以,我們有上面的axis=1
。 此外,規范將是 1 級向量。 因此,在這種情況下,要轉換為形狀(3,1)
,就需要 reshape。 另外,上面的公式是針對向量的,當你應用到矩陣時,“轉置部分會排在第二位”。
現在在這種情況下,q 只不過是 piteslf。 所以,余弦相似度將是
np.dot(p, p.T)
array([[1. , 0.91465912, 0.87845859],
[0.91465912, 1. , 0.99663684],
[0.87845859, 0.99663684, 1. ]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.