【转载保存】在python中如何用word2vec来计算句子的相似度
生活随笔
收集整理的這篇文章主要介紹了
【转载保存】在python中如何用word2vec来计算句子的相似度
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在python中,如何使用word2vec來計算句子的相似度呢?
第一種解決方法
如果使用word2vec,需要計算每個句子/文檔中所有單詞的平均向量,并使用向量之間的余弦相似度來計算句子相似度,代碼示例如下:
import numpy as np from scipy import spatialindex2word_set = set(model.index2word)def avg_feature_vector(sentence, model, num_features, index2word_set):words = sentence.split()feature_vec = np.zeros((num_features, ), dtype='float32')n_words = 0for word in words:if word in index2word_set:n_words += 1feature_vec = np.add(feature_vec, model[word])if (n_words > 0):feature_vec = np.divide(feature_vec, n_words)return feature_vec計算相似度:
s1_afv = avg_feature_vector('this is a sentence', model=model, num_features=300, index2word_set=index2word_set) s2_afv = avg_feature_vector('this is also sentence', model=model, num_features=300, index2word_set=index2word_set) sim = 1 - spatial.distance.cosine(s1_afv, s2_afv) print(sim)> 0.915479828613?
第二種解決思路
Word2Vec有一些擴展用于比較較長的文本,可以解決短語或句子比較的問題。其中之一是paragraph2vec或doc2vec。
詳見“分布式句子和文檔表示”http://cs.stanford.edu/~quocle/paragraph_vector.pdf
http://rare-technologies.com/doc2vec-tutorial/
?
其他解決方法
要計算句子相似度,也可以使用Word Mover距離算法。這里是一個easy description about WMD。
#load word2vec model, here GoogleNews is used model = gensim.models.KeyedVectors.load_word2vec_format('../GoogleNews-vectors-negative300.bin', binary=True) #two sample sentences s1 = 'the first sentence' s2 = 'the second text'#calculate distance between two sentences using WMD algorithm distance = model.wmdistance(s1, s2)print ('distance = %.3f' % distance)P.s .:如果您遇到有關導入pyemd庫的錯誤,可以使用以下命令進行安裝:
pip install pyemd另外,也可以使用sklearn cosine_similarity加載兩個句子向量并計算相似度。
參考文獻
- How to calculate the sentence similarity using word2vec model of gensim with python
文章地址:?https://vimsky.com/article/3677.html
總結
以上是生活随笔為你收集整理的【转载保存】在python中如何用word2vec来计算句子的相似度的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转载保存】hadoop三个配置文件的参
- 下一篇: opencv常用函数