散点图“最佳拟合”线的算法

我正在使用MSChart控件在C#中编写一个小应用程序来执行X和Y数据点集的Scatter Plots。 其中一些可能相当大(数百个数据点)。

想要询问是否有一个“标准”算法来绘制点上最合适的线。 我想将X数据点划分为预定数量的集合,比如10或20,并且对于每个集合,取相应Y值和中间X值的平均值,依此类推以创建该行。 这是正确的方法吗?

我搜索了现有的线程,但它们似乎都是使用像Matlab这样的现有应用程序实现相同的。

谢谢,

使用线性最小二乘算法

public class XYPoint { public int X; public double Y; } class Program { public static List GenerateLinearBestFit(List 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 points = new List() { 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 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); } } } 

是。 您将需要使用线性回归 ,特别是简单线性回归 。

该算法基本上是:

  • 假设存在一条最佳拟合线, y = ax + b
  • 对于每个点,您希望最小化它们与此线的距离
  • 计算距离线的每个点的距离,并计算距离(通常我们使用距离的平方来更严重地惩罚距离线更远的点)
  • 找到ab的值,使用基本微积分最小化所得到的方程(应该只有一个最小值)

维基百科页面将为您提供所需的一切。