python计算协方差_在Python中计算协方差

要计算协方差,您需要类似下面这样的内容,它有一个嵌套循环,遍历每个列表,并使用协方差公式累积协方差。在# let's get the mean of `X` (add all the vals in `X` and divide by

# the length

x_mean = float(sum(X)) / len(X)

# now, let's get the mean for `Y`

y_mean = float(sum(Y)) / len(Y)

# initialize the covariance to 0 so we can add it up

cov = 0

# we'll use a nested loop structure the outer loop can be through `Y`

# or `X`, it doesn't matter in this case

# we'll use python's `enumerate`, which lets us iterate through the `list`

# using a `tuple` that contains (the_current_index, the_current_element),

# or in `C`/`Java` terms, `(i, arr[i])`

for y_idx,y in enumerate(Y):

for x_idx,x in enumerate(X):

# the covariance is defined by the following equation

# you don't need to loop through `P` the outer list

# contains 2 elements, which is the size of `X`, and

# the inner list contains 3 elements, which is the size of `Y`

cov += (x - x_mean) * (y - y_mean) * P[x_idx][y_idx]

print cov # => 0.25

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值