樣本回歸模型: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 }