如何在python中获得两个向量的相关性 [英] How to get correlation of two vectors in python

查看:85
本文介绍了如何在python中获得两个向量的相关性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在matlab中我使用

In matlab I use

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

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

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?

推荐答案

文档表明 numpy.correlate 不是你要找的:

The docs indicate that numpy.correlate is not what you are looking for:

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 try 做到这一点:

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

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.        ]]

这篇关于如何在python中获得两个向量的相关性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆