C# 如何计算两个给定向量之间的Pearson相关性?
我必须用C语言编写代码# 你能在下面的例子中一步一步地解释吗C# 如何计算两个给定向量之间的Pearson相关性?,c#,correlation,pearson,pearson-correlation,C#,Correlation,Pearson,Pearson Correlation,我必须用C语言编写代码# 你能在下面的例子中一步一步地解释吗 vector 1 : [0.3, 0, 1.7, 2.2] vector 2 : [0, 3.3, 1.2, 0] 非常感谢你 这将用于文档集群,这是我在Java版本上的答案的改编 对于C#。首先,皮尔逊相关性是 假设两个向量(设为IEnumerable)长度相同 private static double Correlation(IEnumerable<Double> xs, IEnumerable<Do
vector 1 : [0.3, 0, 1.7, 2.2]
vector 2 : [0, 3.3, 1.2, 0]
非常感谢你
这将用于文档集群,这是我在Java版本上的答案的改编
对于C#。首先,皮尔逊相关性是
假设两个向量(设为IEnumerable
)长度相同
private static double Correlation(IEnumerable<Double> xs, IEnumerable<Double> ys) {
// sums of x, y, x squared etc.
double sx = 0.0;
double sy = 0.0;
double sxx = 0.0;
double syy = 0.0;
double sxy = 0.0;
int n = 0;
using (var enX = xs.GetEnumerator()) {
using (var enY = ys.GetEnumerator()) {
while (enX.MoveNext() && enY.MoveNext()) {
double x = enX.Current;
double y = enY.Current;
n += 1;
sx += x;
sy += y;
sxx += x * x;
syy += y * y;
sxy += x * y;
}
}
}
// covariation
double cov = sxy / n - sx * sy / n / n;
// standard error of x
double sigmaX = Math.Sqrt(sxx / n - sx * sx / n / n);
// standard error of y
double sigmaY = Math.Sqrt(syy / n - sy * sy / n / n);
// correlation is just a normalized covariation
return cov / sigmaX / sigmaY;
}
它是Java实现,但很容易适应C#
// -0.539354840012899
Double result = Correlation(
new Double[] { 0.3, 0, 1.7, 2.2 },
new Double[] { 0, 3.3, 1.2, 0 });