1.Point结构
在编写C#窗体应用程序时,因为引用了System.Drawing命名空间,其中自带了Point结构,本文中的例子是一个控制台应用程序,因此自己制作了一个Point结构
/// <summary>
/// 二维笛卡尔坐标系坐标
/// </summary>
public struct Point
{
public double X;
public double Y;
public Point(double x = 0, double y = 0)
{
X = x;
Y = y;
}
}
2.线性回归
/// <summary>
/// 对一组点通过最小二乘法进行线性回归
/// </summary>
/// <param name="parray"></param>
public static void LinearRegression(Point[] parray)
{
//点数不能小于2
if (parray.Length < 2)
{
Console.WriteLine("点的数量小于2,无法进行线性回归");
return;
}
//求出横纵坐标的平均值
double averagex = 0, averagey = 0;
foreach (Point p in parray)
{
averagex += p.X;
averagey += p.Y;
}
averagex /= parray.Length;
averagey /= parray.Length;
//经验回归系数的分子与分母
double numerator = 0;
double denominator = 0;
foreach (Point p in parray)
{
numerator += (p.X - averagex) * (p.Y - averagey);
denominator += (p.X - averagex) * (p.X - averagex);
}
//回归系数b(Regression Coefficient)
double RCB = numerator / denominator;
//回归系数a
double RCA = averagey - RCB * averagex;
Console.WriteLine("回归系数A: " + RCA.ToString("0.0000"));
Console.WriteLine("回归系数B: " + RCB.ToString("0.0000"));
Console.WriteLine(string.Format("方程为: y = {0} + {1} * x",
RCA.ToString("0.0000"), RCB.ToString("0.0000")));
//剩余平方和与回归平方和
double residualSS = 0; //(Residual Sum of Squares)
double regressionSS = 0; //(Regression Sum of Squares)
foreach (Point p in parray)
{
residualSS +=
(p.Y - RCA - RCB * p.X) *
(p.Y - RCA - RCB * p.X);
regressionSS +=
(RCA + RCB * p.X - averagey) *
(RCA + RCB * p.X - averagey);
}
Console.WriteLine("剩余平方和: " + residualSS.ToString("0.0000"));
Console.WriteLine("回归平方和: " + regressionSS.ToString("0.0000"));
}
3.Main函数调用
static void Main(string[] args)
{
//设置一个包含9个点的数组
Point[] array = new Point[9];
array[0] = new Point(0, 66.7);
array[1] = new Point(4, 71.0);
array[2] = new Point(10, 76.3);
array[3] = new Point(15, 80.6);
array[4] = new Point(21, 85.7);
array[5] = new Point(29, 92.9);
array[6] = new Point(36, 99.4);
array[7] = new Point(51, 113.6);
array[8] = new Point(68, 125.1);
LinearRegression(array);
Console.Read();
}
4.运行结果