python-3.x - 我们如何使用 python 找到两个不同的 n-gram 之间的上下文相似性?
问题描述
例如,假设我们有两个词,“great”和“very good”,它们在上下文中彼此相似,但它们是不同的 n-gram(“great”是 unigram,“very good”是 bigram)。我需要一些关于如何构建可以对它们之间的相似性进行评分的 NLP 模型的建议。
解决方案
您可以考虑使用 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 维向量中的所有单词并为每个文本添加它们。
现在您可以使用余弦相似度或任何其他相似度度量。
推荐阅读
- postgresql - 带条件的 PostgreSQL 外键
- tensorflow - 使用 Tensorflow 2 和 Python 3.7 添加两个数字?
- sql - sys.time_zone_info 在 SQL SERVER 中
- asp.net-core - 如何从 ASP.NET Core Web API 应用程序中的 IIS 站点文件夹获取文件
- typescript - Typescript - 根据参数返回通用接口类型
- php - 无法使用 PHP Simple HTML DOM 获取可用产品信息
- java - 如何限制 Java ServiceLoader 仅加载测试包中定义的服务提供者
- count - 使用 DAX 识别该记录是否在数据集中列出的第 1、2、3 次等,并用该数字标记记录
- php - 代码不起作用(isset 复选框 foreach)
- java - 模糊后如何返回原始 SimpleDraweeView