样本回归模型:
其中ei为样本(Xi, Yi)的误差
平方损失函数:
yi为实际值,^yi为预测值
则通过Q最小确定这条直线,即确定,以
为变量,把它们看作是Q的函数,就变成了一个求极值的问题,可以通过求导数得到。求Q对两个待估参数的偏导数:
根据数学知识我们知道,函数的极值点为偏导为0的点。
解得:
这就是最小二乘法的解法,就是求得平方损失函数的极值点。
/* 2 最小二乘法C++实现 3 参数1为输入文件 4 输入 : x 5 输出: 预测的y 6 */ 7 #include8 #include 9 #include 10 using namespace std;11 12 class LeastSquare{13 double a, b;14 public:15 LeastSquare(const vector & x, const vector & y)16 {17 double t1=0, t2=0, t3=0, t4=0;18 for(int i=0; i x;51 ifstream in(argv[1]);52 for(double d; in>>d; )53 x.push_back(d);54 int sz = x.size();55 vector y(x.begin()+sz/2, x.end());56 x.resize(sz/2);57 LeastSquare ls(x, y);58 ls.print();59 60 cout<<"Input x:\n";61 double x0;62 while(cin>>x0)63 {64 cout<<"y = "< <