使用 python 的句子的 word2vec 查找 2 个句子之间的相似性



我想使用 word2vector 计算两个句子之间的相似性,我正在尝试获取句子的向量,以便我可以计算句子向量的平均值以找到余弦相似性。 我已经尝试过这段代码,但它不起作用。 它给出带有 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

我认为您要实现的目标如下:

  1. 从word2vec获取句子中每个单词的向量表示。
  2. 平均句子的所有词向量以获得句子表示。
  3. 计算两个句子的向量之间的余弦相似性。

虽然2 和 3 的代码对我来说总体上看起来不错(虽然没有测试过(,但问题可能出在步骤 1 中。你在代码中做什么

word2vec_model=gensim.models.Word2Vec(sentences, size=100, min_count=5)

是初始化一个新的 word2vec 模型。如果你调用word2vec_model.train(),gensim 会在你的句子上训练一个新模型,这样你以后就可以为每个单词使用生成的向量。但是,为了获得捕获相似性的有用词向量,您通常需要在大量数据上训练word2vec模型 - Google提供的模型是在1000亿个单词上进行训练的。

你可能想做的是使用一个预先训练的word2vec模型,并在你的代码中与gensim一起使用。根据 gensim 的文档,这可以通过KeyedVectors.load_word2vec_format方法完成。

您的第二部分(将文本转换为特征向量(是错误的。 您必须替换:

featureVec = np.ones((num_features,), dtype="float32")

featureVec = np.zeros((num_features,), dtype="float32").

如果在字典(index2word_set(中找不到任何单词,那么它应该给它们全部零。 这解决了我的问题。😌 🌟

最新更新