(C#)直线的最小二乘法线性回归

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.运行结果

095145_IIEU_1425762.png

转载于:https://my.oschina.net/Tsybius2014/blog/272736

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值