word2vectorsを使って2つの文の類似度を計算したいのですが、文のベクトルを取得しようとしていますコサイン類似度。私はこのコードを試しましたが、動作しません。出力は1の文ベクトルを与える。私はsentence_1_avg_vectorの文の実際のベクトルを& sentence_2_avg_vectorにしたい。Find Pythonで文のword2vecを使って2文の類似度を調べる
コード:
#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ベクトルを検索して平均化したり、最初から計算したりして、文章のベクトル表現を計算しますか?あなたのコードは、あなたが後者を試しているように見えます...しかし、私はあなたがただ2つの文から有用な埋め込みを学ぶことはできないと思います。人々は通常、そのために数百万語を使用します。 – Tobias
おそらくこれが役に立ちます。 – alvas
これは実際には2つのセンテンスではありません。私のデータセットには8つのlacs +行の文が含まれています。便宜上私のコンセプトを伝えるためにサンプルデータをここに挙げました... –