在python中如何用word2vec來計算句子的相似度

原文鏈接:https://vimsky.com/article/3677.html

在python中,如何使用word2vec來計算句子的相似度呢?
第一種解決方法

如果使用word2vec,需要計算每個句子/文檔中所有單詞的平均向量,並使用向量之間的餘弦相似度來計算句子相似度,代碼示例如下

import numpy as np
from scipy import spatial

index2word_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 = 0
    for word in words:
        if word in index2word_set:
            n_words += 1
            feature_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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章