如何在python中获得两个向量的相关性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19428029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get correlation of two vectors in python
提问by Luke Makk
In matlab I use
在matlab中我使用
a=[1,4,6]
b=[1,2,3]
corr(a,b)
which returns .9934. I've tried numpy.correlate
but it returns something completely different. What is the simplest way to get the correlation of two vectors?
返回 0.9934。我试过了,numpy.correlate
但它返回了完全不同的东西。获得两个向量的相关性的最简单方法是什么?
回答by Hooked
The docs indicate that numpy.correlate
is not what you are looking for:
文档表明这numpy.correlate
不是您要查找的内容:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
相反,正如其他评论所建议的那样,您正在寻找Pearson 相关系数。要做到这一点 scipy 尝试:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
这给
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
您还可以使用numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
这给出:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]