using
System.Collections.Generic;
using System.Linq;
using System.Text;
using
System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static double AverageX = 0,
AverageY = 0;
static double Numerator = 0;
static double Denominator = 0;
static double RCB;
static double RCA;
static double Residual_SS = 0;
static double Regression_SS = 0;
static void Main(string[] args)
{
double[,] Point = new double[,]
{
{0, 67.37},
{4, 71.0},
{10, 76.3},
{15, 80.6},
{21, 85.7},
{29, 92.9},
{36, 99.4},
{51, 110.6},
{68, 126.1}
};
LinearRegression(Point);
Console.Read();
}
public static void LinearRegression(double[,] point)
{
if (point.GetLength(0)
< 2)
{
Console.WriteLine("點的數量小於2,無法進行線性回歸");
return;
}
for (int i = 0; i <
point.GetLength(0); i++)
{
AverageX += point[i, 0];
AverageY += point[i, 1];
}
AverageX /= point.GetLength(0);
AverageY /= point.GetLength(0);
Console.WriteLine("平均X:
{0}\n平均Y: {1}", AverageX,
AverageY);
for (int i = 0; i <
point.GetLength(0); i++)
{
Numerator += (point[i, 0] -
AverageX) * (point[i, 1] - AverageY);
Denominator += (point[i,0] -
AverageX) * (point[i,0] - AverageX);
}
RCB = Numerator / Denominator;
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")));
for (int i = 0; i <
point.GetLength(0); i++)
{
Residual_SS += (point[i, 1] -
RCA - RCB * point[i, 0]) * (point[i, 1] - RCA - RCB * point[i, 0]);
Regression_SS += (RCA + RCB *
point[i, 0] - AverageY) * (RCA + RCB * point[i, 0] - AverageY);
}
Console.WriteLine("剩餘平方和: " + Residual_SS.ToString("0.0000"));
Console.WriteLine("回歸平方和: " + Regression_SS.ToString("0.0000"));
}
}
}
沒有留言:
張貼留言