最小二乘法

样本回归模型:ios

                                     其中ei为样本(Xi, Yi)的偏差函数

   平方损失函数:spa

                      

yi为实际值,^yi为预测值code

   则经过Q最小肯定这条直线,即肯定,以为变量,把它们看做是Q的函数,就变成了一个求极值的问题,能够经过求导数获得。求Q对两个待估参数的偏导数:ci

                       

    根据数学知识咱们知道,函数的极值点为偏导为0的点。get

    解得:数学

                   

 

这就是最小二乘法的解法,就是求得平方损失函数的极值点。io

 

 

/*
 2 最小二乘法C++实现
 3 参数1为输入文件
 4 输入 : x
 5 输出: 预测的y  
 6 */
 7 #include<iostream>
 8 #include<fstream>
 9 #include<vector>
10 using namespace std;
11 
12 class LeastSquare{
13     double a, b;
14 public:
15     LeastSquare(const vector<double>& x, const vector<double>& y)
16     {
17         double t1=0, t2=0, t3=0, t4=0;
18         for(int i=0; i<x.size(); ++i)
19         {
20             t1 += x[i]*x[i];
21             t2 += x[i];
22             t3 += x[i]*y[i];
23             t4 += y[i];
24         }
25         a = (t3*x.size() - t2*t4) / (t1*x.size() - t2*t2);  // 求得β1 
26         b = (t1*t4 - t2*t3) / (t1*x.size() - t2*t2);        // 求得β2
27     }
28 
29     double getY(const double x) const
30     {
31         return a*x + b;
32     }
33 
34     void print() const
35     {
36         cout<<"y = "<<a<<"x + "<<b<<"\n";
37     }
38 
39 };
40 
41 int main(int argc, char *argv[])
42 {
43     if(argc != 2)
44     {
45         cout<<"Usage: DataFile.txt"<<endl;
46         return -1;
47     }
48     else
49     {
50         vector<double> x;
51         ifstream in(argv[1]);
52         for(double d; in>>d; )
53             x.push_back(d);
54         int sz = x.size();
55         vector<double> 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 = "<<ls.getY(x0)<<endl;
65             cout<<"Input x:\n";
66         }
67     }
68 }
相关文章
相关标签/搜索