[英]Efficient way to compute cosine similarity between 1D array and all rows in a 2D array
[英]Compute cosine similarity between 3D numpy array and 2D numpy array
我有一個形狀為(m,n,300)的3D numpy數組A和一個形狀為(p,300)的2D numpy數組B。
對於3D數組中的m個(n,300)矩陣,我想用2D numpy數組計算其余弦相似度矩陣。 目前,我正在執行以下操作:
result = []
for sub_matrix in A:
result.append(sklearn.metrics.pairwise.cosine_similarity(sub_matrix, B)
sklearn cosine_similarity函數不支持3D數組的運算,因此,有沒有一種不使用for循環的更有效的計算方法?
您可以重塑為2D
並使用相同的功能-
from sklearn.metrics.pairwise import cosine_similarity
m,n = A.shape[:2]
out = cosine_similarity(A.reshape(m*n,-1), B).reshape(m,n,-1)
最后的整形后,輸出將為3D
,這是對result
進行數組轉換后的result
。
樣品運行-
In [336]: np.random.seed(0)
...: A = np.random.rand(5,4,3)
...: B = np.random.rand(2,3)
...:
...: result = []
...: for sub_matrix in A:
...: result.append(cosine_similarity(sub_matrix, B))
...: out_org = np.array(result)
...:
...: from sklearn.metrics.pairwise import cosine_similarity
...:
...: m,n = A.shape[:2]
...: out = cosine_similarity(A.reshape(m*n,-1), B).reshape(m,n,-1)
...:
...: print np.allclose(out_org, out)
True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.