87

在matlab中我使用

a=[1,4,6]
b=[1,2,3]
corr(a,b)

返回 .9934。我试过numpy.correlate了,但它返回的东西完全不同。获得两个向量相关性的最简单方法是什么?

4

1 回答 1

179

文档表明这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.

相反,正如其他评论所建议的那样,您正在寻找Pearson 相关系数。要使用 scipy 尝试执行此操作:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print(pearsonr(a,b))

这给

(0.99339926779878274, 0.073186395040328034)

您还可以使用numpy.corrcoef

import numpy
print(numpy.corrcoef(a,b))

这给出了:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]
于 2013-10-17T14:27:28.327 回答