[英]Python - How to find a correlation between two vectors?
Given two vectors X and Y , I have to find their correlation, ie their linear dependence/independence. 给定两个向量X和Y ,我必须找到它们的相关性,即它们的线性依赖性/独立性。 Both vectors have equal dimension.
两个向量具有相同的维度。 The result should be a floating point number from [-1.0 .. 1.0].
结果应该是[-1.0 .. 1.0]的浮点数。
Example: 例:
X=[-1, 2, 0]
Y=[ 4, 2, -0.3]
Find y = cor(X,Y) such that y belongs to [-1.0 .. 1.0] . 求y = cor(X,Y)使得y属于[-1.0 .. 1.0] 。
It should be a simple construction involving a list-comprehension. 它应该是一个涉及列表理解的简单构造。 No external library is allowed.
不允许使用外部库。
UPDATE: ok, if the dot product is enough, then here is my solution: 更新:好的,如果点积足够,那么这是我的解决方案:
nX = 1/(sum([x*x for x in X]) ** 0.5)
nY = 1/(sum([y*y for y in Y]) ** 0.5)
cor = sum([(x*nX)*(y*nY) for x,y in zip(X,Y) ])
right? 对?
Since range is supposed to be [-1, 1]
I think that the Pearson Correlation can be ok for your purposes. 由于范围应该是
[-1, 1]
我认为Pearson Correlation可以满足您的需要。
Also dot-product would work but you'll have to normalize vectors before calculating it and you can have a -1,1 range just if you have also negative values.. otherwise you would have 0,1 点积也可以工作,但你必须在计算之前对矢量进行标准化,并且如果你还有负值,你可以得到-1,1范围。否则你会得到0,1
Sounds like a dot product to me. 对我来说听起来像点产品 。
Solve the equation for the cosine of the angle between the two vectors, which is always in the range [-1, 1], and you'll have what you want. 求解两个向量之间角度余弦的等式,它始终在[-1,1]范围内,你就可以得到你想要的。
It's equal to the dot product divided by the magnitudes of two vectors. 它等于点积除以两个矢量的大小。
Don't assume because a formula is algebraically correct that its direct implementation in code will work. 不要假设,因为公式在代数上是正确的,它在代码中的直接实现将起作用。 There can be numerical problems with some definitions of correlation.
一些相关定义可能存在数值问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.