[英]Finding Similarity between 2 sentences using word2vec of sentence with python
我想使用 word2vectors 计算两个句子之间的相似度,我试图获取一个句子的向量,以便我可以计算一个句子向量的平均值以找到余弦相似度。 我试过这段代码,但它不起作用。 它的输出给出了带有 1 的句子向量。 我想要sentence_1_avg_vector 和sentence_2_avg_vector 中句子的实际向量。
代码:
#DataSet#
sent1=[['What', 'step', 'step', 'guide', 'invest', 'share', 'market', 'india'],['What', 'story', 'Kohinoor', 'KohiNoor', 'Diamond']]
sent2=[['What', 'step', 'step', 'guide', 'invest', 'share', 'market'],['What', 'would', 'happen', 'Indian', 'government', 'stole', 'Kohinoor', 'KohiNoor', 'diamond', 'back']]
sentences=sent1+sent2
#''''Applying Word2vec''''#
word2vec_model=gensim.models.Word2Vec(sentences, size=100, min_count=5)
bin_file="vecmodel.csv"
word2vec_model.wv.save_word2vec_format(bin_file,binary=False)
#''''Making Sentence Vectors''''#
def avg_feature_vector(words, model, num_features, index2word_set):
#function to average all words vectors in a given paragraph
featureVec = np.ones((num_features,), dtype="float32")
#print(featureVec)
nwords = 0
#list containing names of words in the vocabulary
index2word_set = set(model.wv.index2word)# this is moved as input param for performance reasons
for word in words:
if word in index2word_set:
nwords = nwords+1
featureVec = np.add(featureVec, model[word])
print(featureVec)
if(nwords>0):
featureVec = np.divide(featureVec, nwords)
return featureVec
i=0
while i<len(sent1):
sentence_1_avg_vector = avg_feature_vector(mylist1, model=word2vec_model, num_features=300, index2word_set=set(word2vec_model.wv.index2word))
print(sentence_1_avg_vector)
sentence_2_avg_vector = avg_feature_vector(mylist2, model=word2vec_model, num_features=300, index2word_set=set(word2vec_model.wv.index2word))
print(sentence_2_avg_vector)
sen1_sen2_similarity = 1 - spatial.distance.cosine(sentence_1_avg_vector,sentence_2_avg_vector)
print(sen1_sen2_similarity)
i+=1
此代码给出的输出:
[ 1. 1. .... 1. 1.]
[ 1. 1. .... 1. 1.]
0.999999898245
[ 1. 1. .... 1. 1.]
[ 1. 1. .... 1. 1.]
0.999999898245
我认为您要实现的目标如下:
虽然 2 和 3 的代码对我来说总体上看起来不错(虽然还没有测试过),但问题可能出在第 1 步。你在代码中做什么
word2vec_model=gensim.models.Word2Vec(sentences, size=100, min_count=5)
是初始化一个新的 word2vec 模型。 如果您随后调用word2vec_model.train()
,gensim 将在您的句子上训练一个新模型,以便您之后可以使用每个单词的结果向量。 但是,为了获得有用的词向量来捕捉相似性之类的东西,你通常需要在大量数据上训练 word2vec 模型——谷歌提供的模型是在 1000 亿个单词上训练的。
您可能想要做的是使用预训练的 word2vec 模型,并在您的代码中将其与 gensim 一起使用。 根据gensim的文档,这可以通过KeyedVectors.load_word2vec_format
方法来完成。
您的第二部分(将文本转换为特征向量)是错误的。 你必须更换:
featureVec = np.ones((num_features,), dtype="float32")
与
featureVec = np.zeros((num_features,), dtype="float32")
。
如果在字典 (index2word_set) 中没有找到任何单词,那么它应该给它们全零。 那解决了我的问题。 😌🌟
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.