我想使用 word2vectors 计算两个句子之间的相似度,我试图获取一个句子的向量,以便我可以计算句子向量的平均值以找到余弦相似度。我已经尝试过这段代码,但它不起作用。它的输出给出带有 1 的句子向量。我想要句子_1_avg_向量和句子_2_avg_向量中句子的实际向量。
代码:
#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
Run Code Online (Sandbox Code Playgroud)
该代码给出的输出:
[ 1. 1. .... 1. 1.]
[ 1. 1. .... 1. 1.]
0.999999898245
[ 1. 1. .... 1. 1.]
[ 1. 1. .... 1. 1.]
0.999999898245
Run Code Online (Sandbox Code Playgroud)
我认为您想要实现的目标如下:
虽然 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方法来完成。