C#直線的最小二乘法線性回歸運算實例。本站提示廣大學習愛好者:(C#直線的最小二乘法線性回歸運算實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#直線的最小二乘法線性回歸運算實例正文
本文實例講述了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#法式設計有所贊助。