C#线性回归函数,离散点斜率⼆元⼀次,多元多次⽅程算法(⽤于离散点求取整体斜率):
/// <summary>
/// ⼆维笛卡尔坐标系坐标
/// </summary>
public struct Point
{
public double X;
public double Y;
public Point(double x, double y)
{
X = x;
Y = y;
}
}
/// <summary>
/// 对⼀组点通过最⼩⼆乘法进⾏线性回归
/// </summary>
/// <param name="parray"></param>
public Point LinearRegression(Point[] parray)
{
Point tempPoint = new Point();
//点数不能⼩于2
if (parray.Length < 2)
{
Console.WriteLine("点的数量⼩于2,⽆法进⾏线性回归");
return tempPoint;
}
//求出横纵坐标的平均值
double averagex = 0, averagey = 0;
foreach (Point p in parray)
writeline函数{
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;
//string result= "y=" + RCA.ToString("F3") + "x+" + RCB.ToString("F3");
tempPoint.X = RCB;
tempPoint.Y = RCA;
return tempPoint;
//Console.WriteLine("回归系数A: " + RCA.ToString("0.0000"));
//Console.WriteLine("回归系数B: " + RCB.ToString("0.0000"));
//Console.WriteLine(string.Format("⽅程为: y = {0} + {1} * x",
/
/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")); }

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。