加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#直线的最小二乘法线性回归运算实例

发布时间:2020-12-15 05:49:53 所属栏目:百科 来源:网络整理
导读:本篇章节讲解C#直线的最小二乘法线性回归运算方法。供大家参考研究。具体如下: 1.Point结构 在编写C#窗体应用程序时,因为引用了System.Drawing命名空间,其中自带了Point结构,本文中的例子是一个控制台应用程序,因此自己制作了一个Point结构 ///

本篇章节讲解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.运行结果

希望本文所述对大家的C#程序设计有所帮助。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读