日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

【转载保存】在python中如何用word2vec来计算句子的相似度

發布時間:2024/8/23 python 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【转载保存】在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来计算句子的相似度的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。