python - 比较 NumPy 数组的相似性

标签 python numpy gensim

我有一个形状为 (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)

关于python - 比较 NumPy 数组的相似性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56908407/

相关文章:

python - 为什么这个巨大的(非稀疏的)numpy 矩阵适合 RAM

python-2.7 - 过滤掉在 gensim 字典中恰好出现一次的标记

python - 交互式 shell paramiko 如何像 exec_command 一样读取输入

python - 从 python 中的类似 cron 的调度程序中删除事件

python - 在 python 中通过数据库正确调用和使用 Linux find

python - Numpy 和 diff()

python - 根据单个单元格的条件从 numpy 数组中删除列

python - 如何格式化数据以供 seaborn 使用

python - 使用 Gensim 中的 filter_extremes 按频率过滤 token

python - 训练gensim word2vec模型后单词不在词汇表中,为什么?