Calculating Mahalanobis distance with C#

匿名 (未验证) 提交于 2019-12-03 09:17:17

问题:

I'm trying to calculate the mahalanobis distance with c#. I can't find any real good examples online and I'm new to C#. I am especially having trouble getting the covariance matrix to run right. Any help would be appreciated. Thanks!

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;     }  }}

回答1:

In the i loop in the twoPassCovariance method, I believe you should loop to i < n rather than i < 2.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!