2012-10-18 50 views
4

我正在用C#編寫一個小應用程序,使用MSChart控件做X和Y數據點集的散點圖。其中一些可能相當大(數百個數據點)。散點圖「最適合」線的算法

想知道是否有一個「標準」算法來繪製一個最佳擬合線。我正在考慮將X數據點分成預定義數量的集合,比如10或20,並且對於每個集合,取對應的Y值和中間的X值的平均值,以此類推以創建該行。這是一個正確的方法嗎?

我已經搜索現有的線程,但他們似乎都是使用現有的應用程序,如Matlab實現相同。

謝謝,

回答

8

使用線性最小二乘法

public class XYPoint 
{ 
    public int X; 
    public double Y; 
} 

class Program 
{ 
    public static List<XYPoint> GenerateLinearBestFit(List<XYPoint> points, out double a, out double b) 
    { 
     int numPoints = points.Count; 
     double meanX = points.Average(point => point.X); 
     double meanY = points.Average(point => point.Y); 

     double sumXSquared = points.Sum(point => point.X * point.X); 
     double sumXY = points.Sum(point => point.X * point.Y); 

     a = (sumXY/numPoints - meanX * meanY)/(sumXSquared/numPoints - meanX * meanX); 
     b = (a * meanX - meanY); 

     double a1 = a; 
     double b1 = b; 

     return points.Select(point => new XYPoint() { X = point.X, Y = a1 * point.X - b1 }).ToList(); 
    } 

    static void Main(string[] args) 
    { 
     List<XYPoint> points = new List<XYPoint>() 
            { 
             new XYPoint() {X = 1, Y = 12}, 
             new XYPoint() {X = 2, Y = 16}, 
             new XYPoint() {X = 3, Y = 34}, 
             new XYPoint() {X = 4, Y = 45}, 
             new XYPoint() {X = 5, Y = 47} 
            }; 

     double a, b; 

     List<XYPoint> bestFit = GenerateLinearBestFit(points, out a, out b); 

     Console.WriteLine("y = {0:#.####}x {1:+#.####;-#.####}", a, -b); 

     for(int index = 0; index < points.Count; index++) 
     { 
      Console.WriteLine("X = {0}, Y = {1}, Fit = {2:#.###}", points[index].X, points[index].Y, bestFit[index].Y); 
     } 
    } 
} 
+0

非常感謝。 – veezi

0

是的。您將需要使用Linear Regression,特別是Simple Linear Regression

的算法基本上是:

  • 假設存在一個最佳擬合線,y = ax + b
  • 爲每個點的,你想從該行
  • 儘量減少他們的距離計算的距離從線上的每個點,並且總和距離(通常我們使用距離的平方來更嚴重地懲罰距線更遠的點)
  • 找到值爲ab的值minimi使用基本微積分得到的方程式(應該只有一個最小值)

維基百科頁面會給你你需要的一切。

+0

謝謝。這些文章當然有用。 – veezi