【发布时间】:2018-02-02 19:46:41
【问题描述】:
我想使用 word2vectors 计算两个句子之间的相似度,我正在尝试获取一个句子的向量,以便我可以计算一个句子向量的平均值来找到余弦相似度。我已经尝试过这段代码,但它不起作用。它的输出给出了带有一个的句子向量。我想要 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
【问题讨论】:
-
您想通过查找和平均预先计算的 word2vec 向量来计算句子的向量表示,还是想从头开始计算它们?您的代码看起来像是在尝试后者……但我认为您不能仅从两句话中学习任何有用的嵌入。人们通常为此使用数百万个单词。
-
也许这会有所帮助。
-
这些实际上不是两个句子.. 我的数据集包含 8 lacs+ 行句子.. 为方便起见,我在这里提到了一些示例数据来传达我的概念...
-
我也面临同样的问题。你能告诉我什么是 mylist1 和 mylist2 吗?