首页 > 解决方案 > 我们如何使用 python 找到两个不同的 n-gram 之间的上下文相似性?

问题描述

例如,假设我们有两个词,“great”和“very good”,它们在上下文中彼此相似,但它们是不同的 n-gram(“great”是 unigram,“very good”是 bigram)。我需要一些关于如何构建可以对它们之间的相似性进行评分的 NLP 模型的建议。

标签: python-3.xmachine-learningnlpsimilarity

解决方案


您可以考虑使用 word2vec 对文本进行编码。

您可以在 Google 新闻上使用预训练模型

wget https://s3.amazonaws.com/dl4j-distribution/GoogleNews-vectors-negative300.bin.gz
gunzip GoogleNews-vectors-negative300.bin.

用法:

import gensim

# Load Google's pre-trained Word2Vec model.
model = gensim.models.Word2Vec.load_word2vec_format('./model/GoogleNews-vectors-negative300.bin', binary=True) 

corpus = [
'good person',
'good human being'
]
# For each sentence in corpus, generate a vector.
# using any similarity measure, you can compute similarity once you encode your text to vector.
corpus_vec = []
for sentence in corpus:
     sent_vec = np.zeros(300)
     for word in sentence:
        sent_vec += model[word]
     corpus_vec.append(sent_vec)

这为每个单词提供了 300 维向量。转换 300 维向量中的所有单词并为每个文本添加它们。

现在您可以使用余弦相似度或任何其他相似度度量。


推荐阅读