微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

计算两个一维数组的成对元素

如何解决计算两个一维数组的成对元素

这是我的问题:

假设我的两个数组是:

import numpy as np
first = np.array(["hello","hello","hellllo"])
second = np.array(["hlo","halo","alle"])

现在我想获取两个数组的每个元素之间的距离矩阵

例如,我的距离函数是:

def diff_len(string1,string2):
    return abs(len(string1) - len(string2))

所以我想得到矩阵:

        hello       hello    hellllo

hlo    result1     result2   result3
halo   result4     result5   result6
alle   result7     result8   result9

所以我要做的是使用Numpy的vectorize函数逐行计算:

vectorize_dist = np.vectorize(diff_len)

first = np.array(["hello","alle"])

vectorize_dist(first,"hlo")
vectorize_dist(first,"halo")
vectorize_dist(first,"alle")

matrix = np.array([vectorize_dist(first,"hlo"),vectorize_dist(first,"halo"),"alle")])
matrix

array([[2,2,4],[1,1,3],3]])

但是为了获得矩阵,我需要执行一个循环来逐行计算,但是我想立即获得矩阵。 实际上,我的两个数组可能非常大,执行循环可能需要太多时间。 而且我还有很多距离要计算,因此我将不得不多次执行该过程,这将更加耗时。

解决方法

您可以为此使用SciPy的cdist

import numpy as np
from scipy.spatial.distance import cdist

def diff_len(string1,string2):
    return abs(len(string1) - len(string2))

first = np.array(["hello","hello","hellllo"])
second = np.array(["hlo","halo","alle"])
d = cdist(first[:,np.newaxis],second[:,lambda a,b: diff_len(a[0],b[0]))
print(d.T)
# [[2. 2. 4.]
#  [1. 1. 3.]
#  [1. 1. 3.]]

请注意,您需要强制转换输出矩阵类型以使其为整数。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。