与列的协方差 [英] Covariance with a columns

查看:98
本文介绍了与列的协方差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个带X.shape=(m,n)的numpy数组X和一个带y.shape=(m,1)的第二列向量y,如何使用for循环计算x的每个列与y的协方差?我希望结果的形状为(m,1)(1,m).

If I have a numpy array X with X.shape=(m,n) and a second column vector y with y.shape=(m,1), how can I calculate the covariance of each column of X with y wihtout using a for loop? I expect the result to be of shape (m,1) or (1,m).

推荐答案

假定输出的形状为(1,n),即对于A的每个列和B,每个covariance操作的标量.因此,对于以n结尾的n列,您可以在此处使用两种使用covariance formula的方法.

Assuming that the output is meant to be of shape (1,n) i.e. a scalar each for covariance operation for each column of A with B and thus for n columns ending up with n such scalars, you can use two approaches here that use covariance formula.

方法1:具有广播功能

np.sum((A - A.mean(0))*(B - B.mean(0)),0)/B.size

方法2:采用矩阵乘法

np.dot((B - B.mean(0)).T,(A - A.mean(0)))/B.size

这篇关于与列的协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆