如何计算两个数据集、值列表之间的协方差?

问题描述 投票:0回答:1
import numpy as np

def cov(x,y):
    if len(x) != len(y):
        return
    a_mean = np.mean(x)
    b_mean = np.mean(y)
    sum = 0 
    for i in range(0, len(x)):
        sum += ((x[i] - a_mean) * (y[i] - b_mean))
    return sum/(len(x))-1
python numpy covariance
1个回答
0
投票
import numpy as np

def cov(x,y):
    if len(x) == len(y): 
        a_mean = np.mean(x) 
        b_mean = np.mean(y) 
        sum = 0 
        for i in range(0, len(x)): 
            sum += ((x[i] - a_mean) * (y[i] - b_mean))
        return sum/(len(x)-1)

    else:
        return 'The length of two lists are not the same'

我对您的代码做了 2 处更改。

  1. 我的条件语句如果两个列表的长度相同找到协方差否则错误消息

  2. 我改变了分母中右括号的位置

© www.soinside.com 2019 - 2024. All rights reserved.