![](/img/trans.png)
[英]How to change the code to find the euclidean distance (not cosine) between words in a word2vec impementation?
[英]Find cosine distance for all pairs of word2vec encodings without using nested loops
我需要為word2vec編碼的所有單詞對計算和存儲余弦距離 。 每個單詞表示為存儲在pandas數據幀中的4 * 1向量,每個元素都在conunuous范圍內[1,9]。 我需要將結果存儲在pandas數據幀中,以便可以在恆定時間內訪問它。
我無法使用pandas library / lambda的apply函數。 使用嵌套循環將需要大約。 9小時(根據tqdm)。
word word1 word2 word3 ...
word1 d11 d12 d13...
word2 d21 d22 d23...
word3 d31 d32 d33...
.
.
.
如果您使用類似Python gensim
庫的東西將預先存在的矢量集(原始word2vec.c格式) KeyedVectors
到其KeyedVectors
表示中,那么原始矢量將在其vectors
屬性中處於numpy數組中。 例如:
kv = KeyedVectors.load_word2vec_format('word_vectors.bin', binary=True)
print(kv.vectors.shape)
然后,您可以使用像scikit-learn
的pairwise_distances()
這樣的庫函數來計算距離矩陣:
from sklearn.metrics import pairwise_distances
distances = pairwise_distances(kv.vectors, metric="cosine")
因為sklearn
例程使用優化的本機數學例程,所以它可能比初始循環純Python方法快得多。 但請注意,得到的距離矩陣可能很大!
(你可以找出哪些詞是在kv.vectors
通過名單插槽kv.index2entity
,或查找插槽用於通過在字典一個字kv.vocab
。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.