2014-12-12 29 views
7

Ben denkleme dayalı kovaryans fonksiyonu kendi uygulaması vardır:numpy.cov() işlevi nasıl uygulanır?

enter image description here

''' 
Calculate the covariance coefficient between two variables. 
''' 

import numpy as np 

X = np.array([171, 184, 210, 198, 166, 167]) 
Y = np.array([78, 77, 98, 110, 80, 69]) 

# Expected value function. 
def E(X, P): 
    expectedValue = 0 
    for i in np.arange(0, np.size(X)): 
     expectedValue += X[i] * (P[i]/np.size(X)) 
    return expectedValue 

# Covariance coefficient function. 
def covariance(X, Y): 
    ''' 
    Calculate the product of the multiplication for each pair of variables 
    values. 
    ''' 
    XY = X * Y 

    # Calculate the expected values for each variable and for the XY. 
    EX = E(X, np.ones(np.size(X))) 
    EY = E(Y, np.ones(np.size(Y))) 
    EXY = E(XY, np.ones(np.size(XY))) 

    # Calculate the covariance coefficient. 
    return EXY - (EX * EY) 

# Display matrix of the covariance coefficient values. 
covMatrix = np.array([[covariance(X, X), covariance(X, Y)], 
[covariance(Y, X), covariance(Y, Y)]]) 
print("My function:", covMatrix) 

# Display standard numpy.cov() covariance coefficient matrix. 
print("Numpy.cov() function:", np.cov([X, Y])) 

Ama sorun, yani benim işlevinden ve numpy.cov() den farklı değerler alıyorum olmasındandır:

My function: [[ 273.88888889 190.61111111] 
[ 190.61111111 197.88888889]] 
Numpy.cov() function: [[ 328.66666667 228.73333333] 
[ 228.73333333 237.46666667]] 

Bunun nedeni nedir? numpy.cov() işlevi nasıl uygulanır? numpy.cov() işlevi iyi uygulanmışsa, ne yapıyorum? Sadece, covariance() fonksiyonumdan elde edilen sonuçların, http://www.naukowiec.org/wzory/statystyka/kowariancja_11.html gibi kovaryans katsayısını hesaplamak için internetteki paper örnekleriyle tutarlı olduğunu söyleyebilirim.

cevap

14

numpy işlevi varsayılan ayar olarak sizin için farklı bir normalleşme var. yerine

>>> np.cov([X, Y], ddof=0) 
array([[ 273.88888889, 190.61111111], 
     [ 190.61111111, 197.88888889]]) 

Referanslar deneyin: Yukarıdaki soru soruldu neden

+0

, bu. "ddof", "serbestlik derecesi" anlamına mı geliyor? – bluevoxel

+0

Evet, doğru – YXD

+2

Aaah, şimdi her şey açık. Çok teşekkürler. – bluevoxel