我正在尝试用c#计算mahalanobis距离。我在网上找不到任何真正好的例子,而且我是 C# 的新手。我尤其无法使协方差矩阵正确运行。任何帮助将不胜感激。谢谢!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MathNet.Numerics.LinearAlgebra.Double;
namespace MahalanobisDistance
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
DenseVector vector1 = new DenseVector(4);
DenseVector vector2 = new DenseVector(4);
DenseMatrix matrix1 = new DenseMatrix(vector1.Count/2);
vector1[0] = 1;
vector1[1] = 2;
vector1[2] = 3;
vector1[3] = 4;
vector2[0] = 2;
vector2[1] = 12;
vector2[2] = 14;
vector2[3] = 18;
matrix1 = p.twoPassCovariance(vector1, vector2);
for(int i = 0; i < matrix1.RowCount; i++)
{
for(int k = 0; k < matrix1.ColumnCount; k++)
{
Console.Write(matrix1[k, i] + " ");
}
//Mahalanobis2(v1, v2, covariance);
Console.Write("n");
}
}
public DenseMatrix twoPassCovariance(DenseVector data1, DenseVector data2)
{
int n = data1.Count;
double mean1 = data1.Average();
double mean2 = data2.Average();
DenseMatrix covariance = new DenseMatrix(data1.Count);
double x;
for(int i = 0; i < 2; i++)
{
for (int k = 0; k < n; k++)
{
double a = data1[i] - mean1;
double b = data2[k] - mean2;
x = a*b;
covariance[i, k] = x;
}
}
covariance.Multiply(1/n);
return covariance;
}
}}
在 twoPassCovariance
方法的 i
循环中,我认为您应该循环到 i < n
而不是i < 2
。