C#直线的最小二乘法线性回归运算实例
程序员文章站
2023-11-04 21:57:16
本文实例讲述了c#直线的最小二乘法线性回归运算方法。分享给大家供大家参考。具体如下:
1.point结构
在编写c#窗体应用程序时,因为引用了system.drawin...
本文实例讲述了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#程序设计有所帮助。
推荐阅读