Python计算两个矩阵中每一行间曼哈顿距离的有效方法

2024-04-20 04:29:09 发布

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

我有两个形状分别为(AxN)(BxN)的矩阵,我想得到一个(AxB)的新矩阵,其中每个元素是每两行之间的曼哈顿距离。你知道吗

我试过使用cdist,但事实上它非常慢,例如,如果我们讨论的是余弦距离,下面的代码对cdist占用两分钟的相同数据需要4秒钟

dotted = matrix_a.dot(matrix_b.transpose())
matrix_a_norms = np.expand_dims(np.linalg.norm(matrix_a, ord=2, axis=1), axis=0)
matrix_b_norms = np.expand_dims(np.linalg.norm(matrix_b, ord=2, axis=1), axis=0)
norm_mat = matrix_a_norms.transpose().dot(matrix_b_norms)
cosine_distance = np.divide(dotted, norm_mat)

所以我想知道,有没有什么可以快速实现的方法,只与曼哈顿的距离相同?你知道吗

编辑:

我试过sklearn的成对曼哈顿,它需要和cdist相同的时间

编辑2:

确切的细节

A=14587B=30228N=300

dtypefloat32

使用sklearn.pairwise.manhattan_distances/cdist(metric='cityblock')平均需要135秒


Tags: 距离normnp矩阵matrixdotexpandtranspose