您可以使用文本相似性搜索相关数据库 tables/fields 吗?

Can you search for related database tables/fields using text similarity?

我正在做一个大学项目,我需要将一个字符串与其他字符串列表进行比较。我想知道我们是否有任何类型的图书馆可以做到这一点。

假设我有一个 table 叫:DOCTORS_DETAILS

其他 Table 名称是: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 

因此我想根据两个相关字符串中存在的相似术语的数量来查找 RELEVENCE。

例如:DOCTOR_DETAILS -> DOCTOR_APPOITMENT(1/2) > DOCTOR_ADDRESS_INFORMATION(1/3) > DOCTOR_SPECILIZATION_DEGREE_INFORMATION (1/4) > PATIENT_INFO (0/2)

语义相似度是一个常见的 NLP 问题。有多种方法可供研究,但它们的核心都将归结为:

  1. 将每段文字转为向量
  2. 测量向量之间的距离,并称更接近的向量更相似

执行第 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)

对于您的特定用例,我的直觉是使用 fasttext。所以,官方网站展示了如何 download some pretrained word vectors, but you will want to download a pretrained model (see this GH issue, use 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 的模型中获得大致相同的精度!