问题描述
这是我的问题:
假设我的两个数组是:
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.]]
请注意,您需要强制转换输出矩阵类型以使其为整数。