我使用gensim
wmdistance
來計算參考句子和其他1000個句子之間的相似度。針對速度(wmdistance)優化Gensim字移動器的距離函數
model = gensim.models.KeyedVectors.load_word2vec_format(
'GoogleNews-vectors-negative300.bin', binary=True)
model.init_sims(replace=True)
reference_sentence = "it is a reference sentence"
other_sentences = [1000 sentences]
index = 0
for sentence in other_sentences:
distance [index] = model.wmdistance(refrence_sentence, other_sentences)
index = index + 1
據gensim
source code,model.wmdistance
返回如下:
emd(d1, d2, distance_matrix)
其中
d1 = # Compute nBOW representation of reference_setence.
d2 = # Compute nBOW representation of other_sentence (one by one).
distance_matrix = see the source code as its a bit too much to paste it here.
此代碼是在兩個方面對我的使用情況下,效率不高。
1)對於參考語句,重複計算距離函數emd(d1, d2, distance_matrix)
的d1(1000次)。
2)這個距離函數被來自不同點的多個用戶調用,它重複這個model.wmdistance(doc1, doc2)
的整個過程,用於相同的other_sentences並且它在計算上是昂貴的。對於這1000個比較,大約需要7-8秒。
因此,我想分離兩個任務。距離的最終計算:emd(d1, d2, distance_matrix)
並準備這些輸入:d1,d2和距離矩陣。由於距離矩陣取決於兩者,因此至少應將其輸入準備與最終矩陣計算分開。
我最初的計劃是創建三個自定義功能:
d1 = prepared1(reference_sentence)
d2 = prepared2(other_sentence)
distance_matrix inputs = prepare inputs
是否有可能與此gensim
功能來做到這一點,或者我應該只是走自己的定製版?任何想法和解決方案以更好的方式處理這個問題?
然後讓我探索RWMD的選項。不是WmdSimilarity(wmd_corpus,model,num_best = 10)與RWMD相同嗎? – utengr
您必須檢查紙張的RWMD定義。儘管開始了一些工作,但我不相信gensim代碼還在執行該優化。要找到最接近的10個項目,它會計算* all *項目的WMD,沒有快捷方式/優化,然後排序以僅返回10個最小距離。 – gojomo
啊,好吧。我將以單獨函數中的單個文檔計算單詞向量和nbow向量的方式進行修改。它可以爲我節省很多時間,因爲我將數千個項目與單個參考進行比較。如果您希望將它作爲gensim中的wmdistance變體,我可以將其作爲功能請求開始。 – utengr