比较 NumPy 数组的相似性

2024-01-24

我有一个形状为 (300,) 的目标 NumPy 数组和一组形状也为 (300,) 的候选数组。这些数组是单词的 Word2Vec 表示;我试图使用向量表示找到与目标单词最相似的候选单词。找到与目标词最相似的候选词的最佳方法是什么?

一种方法是将目标词与候选词之间的元素差异的绝对值相加,然后选择总体绝对差值最低的候选词。例如:

candidate_1_difference = np.subtract(target_vector, candidate_vector)
candidate_1_abs_difference = np.absolute(candidate_1_difference)
candidate_1_total_difference = np.sum(candidate_1_abs_difference)

然而,这似乎很笨拙,而且可能是错误的。有什么更好的方法来做到这一点?

编辑以包含示例向量:

import numpy as np
import gensim

path = 'https://s3.amazonaws.com/dl4j-distribution/GoogleNews-vectors-negative300.bin.gz'


def func1(path):
    #Limited to 50K words to reduce load time
    model = gensim.models.KeyedVectors.load_word2vec_format(path, binary=True, limit=50000)
    context =  ['computer','mouse','keyboard']
    candidates = ['office','house','winter']
    vectors_to_sum = []
    for word in context:
        vectors_to_sum.append(model.wv[word])
    target_vector = np.sum(vectors_to_sum)

    candidate_vector = candidates[0]
    candidate_1_difference = np.subtract(target_vector, candidate_vector)
    candidate_1_abs_difference = np.absolute(candidate_1_difference)
    candidate_1_total_difference = np.sum(candidate_1_abs_difference)
    return candidate_1_total_difference

你所拥有的基本上是正确的。您正在计算 L1 范数,它是绝对差值之和。另一个更常见的选择是计算欧几里德范数或 L2 范数,这是熟悉的平方和平方根的距离度量。

您可以使用numpy.linalg.norm计算不同的范数,默认情况下计算向量的 L-2 范数。

distance = np.linalg.norm(target_vector - candidate_vector)

如果你有一个目标向量和多个候选向量存储在一个列表中,上面的方法仍然有效,但是你需要指定范数的轴,然后你得到一个范数向量,每个候选向量一个。

对于候选向量列表:

distance = np.linalg.norm(target_vector - np.array(candidate_vector), axis=1)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

比较 NumPy 数组的相似性 的相关文章

随机推荐