我正在做一个大学项目,我需要将一个字符串与其他字符串列表进行比较。我想知道我们是否有任何一种图书馆可以做到这一点。
假设我有一个名为:DOCTORS_DETAILS的表
其他表名称是:HOSPITAL_DEPARTMENTS,DOCTOR_APPOINTMENTS,PATIENT_DETAILS,PAYMENTS等。
现在,我要计算其中哪一个与DOCTOR_DETAILS相关性更高?预期的输出可以是,
DOCTOR_APPOINTMENTS - More relevant because of the term doctor matches in both string
PATIENT_DETAILS - The term DETAILS present in both string
HOSPITAL_DEPARTMENTS - least relevant
PAYMENTS - least relevant
因此,我想根据两个相关字符串中存在的相似术语的数量来找到相关性。
例如:DOCTOR_DETAILS-> DOCTOR_APPOITMENT(1/2)> DOCTOR_ADDRESS_INFORMATION(1/3)> DOCTOR_SPECILIZATION_DEGREE_INFORMATION(1/4)> PATIENT_INFO(0/2)
语义相似性是一个常见的NLP问题。有多种方法可以研究,但它们的核心都可以归结为:
执行步骤1的三种可能方法是:
要执行步骤2,您几乎肯定要使用余弦距离。使用Python非常简单,这是a blog post中的实现:
import numpy as np
def cos_sim(a, b):
"""Takes 2 vectors a, b and returns the cosine similarity according
to the definition of the dot product
"""
dot_product = np.dot(a, b)
norm_a = np.linalg.norm(a)
norm_b = np.linalg.norm(b)
return dot_product / (norm_a * norm_b)
对于您的特定用例,我的直觉是使用快速文本。因此,官方站点显示了如何download some pretrained word vectors,但是您将需要下载预训练的模型(see this GH issue,使用https://dl.fbaipublicfiles.com/fasttext/vectors-english/wiki-news-300d-1M-subword.bin.zip),
然后您想要做类似的事情:
import fasttext
model = fasttext.load_model("model_filename.bin")
def order_tables_by_name_similarity(main_table, candidate_tables):
'''Note: we use a fasttext model, not just pretrained vectors, so we get subword information
you can modify this to also output the distances if you need them
'''
main_v = model[main_table]
similarity_to_main = lambda w: cos_sim(main_v, model[w])
return sorted(candidate_tables, key=similarity_to_main, reverse=True)
order_tables_by_name_similarity("DOCTORS_DETAILS", ["HOSPITAL_DEPARTMENTS", "DOCTOR_APPOINTMENTS", "PATIENT_DETAILS", "PAYMENTS"])
# outputs: ['PATIENT_DETAILS', 'DOCTOR_APPOINTMENTS', 'HOSPITAL_DEPARTMENTS', 'PAYMENTS']
[如果您需要将此产品投入生产,那么巨大的模型大小(6.7GB)可能是一个问题。此时,您将要构建自己的模型,并限制模型的大小。 6MB模型可能会获得大致相同的精度!