我有两个形状分别为(AxN)
和(BxN)
的矩阵,我想得到一个(AxB)
的新矩阵,其中每个元素是两行之间的曼哈顿距离。 / p>
我尝试使用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=14587
B=30228
N=300
dtype
是float32
sklearn.pairwise.manhattan_distances
/ cdist(metric='cityblock')
平均需要135秒