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

Numpy:如何将计算协方差的for循环改写为无循环实现

可以用Numpy内置函数实现无循环版本,核心是通过向量化运算批量计算对应行的协方差,完全不需要显式写for循环。

完整实现代码

import numpy as np

m1 = np.array([[1,2,3],[2,2,2]])
m2 = np.array([[2.56, 2.89, 3.76],[1,2,3.95]])

# 计算两个矩阵每行的均值,保留维度适配广播运算
m1_row_mean = m1.mean(axis=1, keepdims=True)
m2_row_mean = m2.mean(axis=1, keepdims=True)

# 协方差默认采用无偏估计,分母为列数-1
col_count = m1.shape[1]
output = ((m1 - m1_row_mean) * (m2 - m2_row_mean)).sum(axis=1) / (col_count - 1)

print(output)

运行结果和你原代码输出完全一致,返回值为[0.6 0. ]。如果需要调整协方差的自由度参数,修改分母为col_count - ddof即可和np.cov的参数逻辑完全对齐。

内容的提问来源于stack exchange,提问作者John_maddon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:36:04