英文:
Euclidean distance matrix of 2 n-d matricies without looping
问题
我听说可以计算两个矩阵数据集的欧几里得距离矩阵(matrix1.shape = (n_1, ...)
和 matrix2.shape = (n_2, ...)
,我们想要计算 n_1 * n_2
欧几里得距离矩阵),而不使用循环。我模糊地认为这与广播有关,但我甚至不确定从何开始。
这是否可能?大多数在线解决方案似乎需要循环。
英文:
I was told it is possible to calculate the euclidean distance matrix of 2 datasets of matrices (matrix1.shape = (n_1, ...)
and matrix2.shape = (n_2, ...)
, where we want to calculate the n_1 * n_2
euclidean distance matrix) without using loops. I vaguely figure it's related to broadcasting, but I'm not sure where to even start.
Is this possible? Most of the solutions online seem to require loops.
答案1
得分: 1
import numpy as np
a = np.random.rand(2,3,4)
b = np.random.rand(5,3,4)
n = np.linalg.norm(a[:,None]-b, axis=(2,3))
The `None` creates a new axis for broadcasting, `axis=(2,3)` tells on which axes to compute the norm from.
英文:
This?
import numpy as np
a = np.random.rand(2,3,4)
b = np.random.rand(5,3,4)
n = np.linalg.norm(a[:,None]-b, axis=(2,3))
The None
creates a new axis for broadcasting, axis=(2,3)
tells on which axes to compute the norm from.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论