You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 10:18:02