欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#直線(xiàn)的最小二乘法線(xiàn)性回歸運(yùn)算實(shí)例

 更新時(shí)間:2015年08月17日 11:18:13   作者:北風(fēng)其涼  
這篇文章主要介紹了C#直線(xiàn)的最小二乘法線(xiàn)性回歸運(yùn)算方法,實(shí)例分析了給定一組點(diǎn),用最小二乘法進(jìn)行線(xiàn)性回歸運(yùn)算的實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下

本文實(shí)例講述了C#直線(xiàn)的最小二乘法線(xiàn)性回歸運(yùn)算方法。分享給大家供大家參考。具體如下:

1.Point結(jié)構(gòu)

在編寫(xiě)C#窗體應(yīng)用程序時(shí),因?yàn)橐昧薙ystem.Drawing命名空間,其中自帶了Point結(jié)構(gòu),本文中的例子是一個(gè)控制臺(tái)應(yīng)用程序,因此自己制作了一個(gè)Point結(jié)構(gòu)

/// <summary>
/// 二維笛卡爾坐標(biāo)系坐標(biāo)
/// </summary>
public struct Point
{
  public double X;
  public double Y;
  public Point(double x = 0, double y = 0)
  {
    X = x;
    Y = y;
  }
}

2.線(xiàn)性回歸

/// <summary>
/// 對(duì)一組點(diǎn)通過(guò)最小二乘法進(jìn)行線(xiàn)性回歸
/// </summary>
/// <param name="parray"></param>
public static void LinearRegression(Point[] parray)
{
  //點(diǎn)數(shù)不能小于2
  if (parray.Length < 2)
  {
    Console.WriteLine("點(diǎn)的數(shù)量小于2,無(wú)法進(jìn)行線(xiàn)性回歸");
    return;
  }
  //求出橫縱坐標(biāo)的平均值
  double averagex = 0, averagey = 0;
  foreach (Point p in parray)
  {
    averagex += p.X;
    averagey += p.Y;
  }
  averagex /= parray.Length;
  averagey /= parray.Length;
  //經(jīng)驗(yàn)回歸系數(shù)的分子與分母
  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);
  }
  //回歸系數(shù)b(Regression Coefficient)
  double RCB = numerator / denominator;
  //回歸系數(shù)a
  double RCA = averagey - RCB * averagex;
  Console.WriteLine("回歸系數(shù)A: " + RCA.ToString("0.0000"));
  Console.WriteLine("回歸系數(shù)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函數(shù)調(diào)用

static void Main(string[] args)
{
  //設(shè)置一個(gè)包含9個(gè)點(diǎn)的數(shù)組
  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.運(yùn)行結(jié)果

希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論