Python中如何高效计算矩阵各列与向量的欧氏距离
Python批量计算矩阵列与向量的欧氏距离
直接使用NumPy的广播机制即可实现无循环的高效计算,完全适配大尺寸矩阵场景,代码如下:
import numpy as np # 示例:2行100列的矩阵A,2行1列的向量b A = np.random.rand(2, 100) b = np.random.rand(2, 1) # 计算平方欧氏距离,输出为100行1列的矩阵,和你要求的计算规则完全匹配 dist_square = np.sum((A - b)**2, axis=0).reshape(-1, 1) # 如果需要开根号得到标准欧氏距离,替换为下行即可 # dist = np.sqrt(np.sum((A - b)**2, axis=0)).reshape(-1, 1)
规则验证(小矩阵示例)
用你问题里的计算逻辑做验证:
A = np.array([[1,2,3],[4,5,6]]) b = np.array([[0],[1]]) dist_square = np.sum((A - b)**2, axis=0).reshape(-1,1) print(dist_square) # 输出结果: # [[10] # [20] # [34]]
符合你给出的d1=(x11-mu1)^2+(x21-mu2)^2的计算规则。
内容的提问来源于stack exchange,提问作者Hermi
相关产品推荐
相关产品推荐

