Skip to main content
 首页 » 编程设计

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

2025年02月15日8sharpest

我想使用 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 

请您参考如下方法:

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

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

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

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

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

您可能想要做的是使用预训练的 word2vec 模型,并在您的代码中将其与 gensim 一起使用。根据documentation of gensim ,这可以通过 KeyedVectors.load_word2vec_format 方法来完成。