本文实例讲述了c#直线的最小二乘法线性回归运算方法。分享给大家供大家参考。具体如下:
1.point结构
在编写c#窗体应用程序时,因为引用了system.drawing命名空间,其中自带了point结构,本文中的例子是一个控制台应用程序,因此自己制作了一个point结构
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/// <summary> /// 二维笛卡尔坐标系坐标 /// </summary> public struct point { public double x; public double y; public point( double x = 0, double y = 0) { x = x; y = y; } } |
2.线性回归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
/// <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函数调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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#程序设计有所帮助。