gpt4 book ai didi

python - 为什么 nump.cov() 和 np.std() 计算的相关性与 np.corrcoef() 计算的结果不同

转载 作者:行者123 更新时间:2023-12-01 09:07:35 26 4
gpt4 key购买 nike

我希望有人能帮我回答为什么numpy.cov()np.std()计算的相关结果与直接计算的结果不同>np.corrcoef().

下面的代码显示了差异

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

X = np.random.rand(50)
Y = np.random.rand(50)

plt.scatter(X,Y)
plt.xlabel('X Value')
plt.ylabel('Y Value')

# taking the relevant value from the matrix returned by np.cov
print 'Correlation: ' + str(np.cov(X,Y)[0,1]/(np.std(X)*np.std(Y)))
# Let's also use the builtin correlation function
print 'Built-in Correlation: ' + str(np.corrcoef(X, Y)[0, 1])

一个示例输出:

Correlation: -0.0972430699897

Built-in Correlation: -0.0952982085899

最佳答案

感谢Brian Borchers的建议

查文档发现差异是由于np.std()的参数ddof(delta自由度)默认为0造成的code>,而 1 用于 np.corrcoef()

修改如下,代码可以生成相同的结果:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

X = np.random.rand(50)
Y = np.random.rand(50)

plt.scatter(X,Y)
plt.xlabel('X Value')
plt.ylabel('Y Value')

# taking the relevant value from the matrix returned by np.cov
print 'Correlation: ' + str(np.cov(X,Y)[0,1]/(np.std(X,ddof=1)*np.std(Y,ddof=1)))
# Let's also use the builtin correlation function
print 'Built-in Correlation: ' + str(np.corrcoef(X, Y)[0, 1])

示例输出:

Correlation: -0.174042621953

Built-in Correlation: -0.174042621953

关于python - 为什么 nump.cov() 和 np.std() 计算的相关性与 np.corrcoef() 计算的结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51923846/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com