2个n维矩阵的欧几里得距离矩阵,无需循环。

huangapple go评论103阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月27日 08:24:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575874.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定