4

我有两个向量,我试图在一个函数中使用它们来只返回样本协方差。谁能帮我修复我的程序?我是 python 和一般编程的新手。

xv= array([8., 9.5, 7.8, 4.2, -7.7, -5.4, 3.2])
yv= array([8.9, 2.0, 4.8, -4.2, 2.7, -3.4, -5.9])

def cov(x,y):
    if (len(x) != len(y)
        [Stop] 
        x.bar = mean(x) 
        y.bar = mean(y) 
        N = len(x)      
    Cov = (sum((x-x.bar)*(y-y.bar))) / (N-1.0) 
    return(Cov) 
4

3 回答 3

1

这是我没有使用外部库的版本。协方差方程来自维基百科:http ://en.wikipedia.org/wiki/Covariance

x = [8., 9.5, 7.8, 4.2, -7.7, -5.4, 3.2]
y = [8.9, 2.0, 4.8, -4.2, 2.7, -3.4, -5.9]

def mean(x):
    return sum(x) / len(x)

def cov(x, y):
    x_mean = mean(x)
    y_mean = mean(y)
    data = [(x[i] - x_mean) * (y[i] - y_mean)
            for i in range(len(x))]
    return sum(data) / (len(data) - 1)

print cov(x, y)
于 2012-10-17T23:10:07.507 回答
0

您可以尝试查看广泛使用的numpy包,用于协方差等操作:http: //docs.scipy.org/doc/numpy/reference/generated/numpy.cov.html

于 2012-10-17T23:02:16.040 回答
0

我以这种方式重写了你的函数:

def cov(x,y):
    if (len(x) != len(y)):
        sys.exit()
    x_bar = float(sum(x)/len(x))
    y_bar = float(sum(y)/len(y))
    N = len(x)
    sum_xy = 0
    for i in range(len(x)):
        sum_xy += (x[i]-x_bar)*(y[i]-y_bar)
    return(sum_xy/(N-1.0))
于 2012-10-17T23:26:22.593 回答