-4
我必須在C#中編寫這個代碼#如何計算2個給定向量之間的Pearson相關性?
你可以在下面給出的例子中逐步解釋嗎?
vector 1 : [0.3, 0, 1.7, 2.2]
vector 2 : [0, 3.3, 1.2, 0]
泰非常
這將在文檔聚類中使用
我必須在C#中編寫這個代碼#如何計算2個給定向量之間的Pearson相關性?
你可以在下面給出的例子中逐步解釋嗎?
vector 1 : [0.3, 0, 1.7, 2.2]
vector 2 : [0, 3.3, 1.2, 0]
泰非常
這將在文檔聚類中使用
這是對的Java版本
How to find correlation between two integer arrays in java
我的回答適應爲C#。首先,皮爾遜相關是
http://en.wikipedia.org/wiki/Correlation_and_dependence
提供了這兩個矢量(讓他們IEnumerable<Double>
)是相同長度的
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;
}
測試:
// -0.539354840012899
Double result = Correlation(
new Double[] { 0.3, 0, 1.7, 2.2 },
new Double[] { 0, 3.3, 1.2, 0 });
HTTP://計算器。 com/questions/28428365/how-to-find-correlation-between-two-integer-arrays-in-java它是Java的實現,但很容易適應C# –