如何在单词/事物词典中找到前N个相似单词?

2024-05-16 01:47:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个要映射的str列表。单词可以是“金属”或“圣帕特里克”。目标是根据该列表映射一个新字符串,并找到前N个类似项。例如,如果我经过“圣帕特里克”,我想捕获“圣帕特里克”或“圣帕特里克”

我知道有gensim和fastText,我有一种直觉,我应该选择余弦相似性(或者如果有其他建议,我洗耳恭听)。我主要研究时间序列,而gensim模型培训似乎不喜欢单词列表

我下一步的目标是什么


Tags: 字符串模型目标列表时间序列相似性单词
1条回答
网友
1楼 · 发布于 2024-05-16 01:47:06

首先,你必须决定你是对语法相似感兴趣还是对语义相似感兴趣

相似性

在本例中,为两个字符串之间的距离打分。有various metrics用于计算编辑距离。Levenshtein距离是最常见的:您可以找到各种python实现,如this

“金”与“好”相似,但与“金属”不相似

语义相似性

在本例中,您可以测量两个字符串中有多少具有相似的含义

fastText和其他单词嵌入也属于这种情况,即使它们也考虑了ortographic方面

“金”与“金属”比“好”更相似

如果列表中的单词数量有限,可以使用预先训练过的existing word embedding。基于此单词嵌入,您可以计算列表中每个单词/句子的单词向量,然后使用余弦相似度将新词向量与列表中的向量进行比较

import fasttext
import numpy as np

# download English pretrained model
fasttext.util.download_model('en', if_exists='ignore')
ft = fasttext.load_model('cc.en.300.bin')

def cos_sim(a, b):
    """Takes 2 vectors a, b and returns the cosine similarity according 
    to the definition of the dot product
    (https://masongallo.github.io/machine/learning,/python/2016/07/29/cosine-similarity.html)
    """
    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)

def compare_word(w, words_vectors):
    """
    Compares new word with those in the words vectors dictionary
    """
    vec=ft.get_sentence_vector(w)
    return {w1:cos_sim(vec,vec1) for w1,vec1 in words_vectors.items()}

# define your word list
words_list=[ "metal", "st. patrick", "health"]

# compute words vectors and save them into a dictionary.
# since there are multiwords expressions, we use get_sentence_vector method
# instead, you can use  get_word_vector method
words_vectors={w:ft.get_sentence_vector(w) for  w in words_list}

# try compare_word function!

compare_word('saint patrick', words_vectors)
# output: {'metal': 0.13774191, 'st. patrick': 0.78390956, 'health': 0.10316559}

compare_word('copper', words_vectors)
# output: {'metal': 0.6028242, 'st. patrick': 0.16589196, 'health': 0.10199054}

compare_word('ireland', words_vectors)
# output: {'metal': 0.092361264, 'st. patrick': 0.3721483, 'health': 0.118174866}

compare_word('disease', words_vectors)
# output: {'metal': 0.10678574, 'st. patrick': 0.07039305, 'health': 0.4192972}

相关问题 更多 >