- 手写高斯牛顿
原理看十四讲第6讲#include<iostream>
#include<eigen3/Eigen/Core>
#include<eigen3/Eigen/Dense>
#include<opencv2/opencv.hpp>
#include<vector>
using namespace std;
int main(int argc,char** argv)
{
double ar=1,br=2,cr=1;
double ae=2,be=-1,ce=5;
cv::RNG rng;
int num=100;
vector<double> X, Y;
for(int i=0;i<num;i++)
{
double x = i*(1.0/100);
double y = exp(ar*x*x+br*x+cr) + rng.gaussian(1.0);
X.push_back(x);
Y.push_back(y);
}
double cost=0, lastcost=0;
for(int iter=0;iter<100;iter++)
{
Eigen::Matrix<double,3,3> H = Eigen::Matrix<double,3,3>::Zero();
Eigen::Matrix<double,3,1> g = Eigen::Matrix<double,3,1>::Zero();
Eigen::Matrix<double,3,1> dx;
cost = 0;
double err=0;
for(int i=0;i<num;i++)
{
double x=X[i];
double y=Y[i];
Eigen::Matrix<double,3,1> J = Eigen::Matrix<double,3,1>::Zero();
J[0] = -x*x*exp(ae*x*x+be*x+ce);
J[1] = -x*exp(ae*x*x+be*x+ce);
J[2] = -exp(ae*x*x+be*x+ce);
err = y-exp(ae*x*x+be*x+ce);
H+=J*J.transpose();
g+=-J*err;
cost+=err*err;
}
dx=H.inverse()*g;
if(iter>0&&cost>=lastcost)
{
cout<<"迭代次数: "<<iter<<endl;
cout<<"cost = "<<lastcost<<endl;
cout<<"a = "<<ae<<"\tb = "<<be<<"\tc = "<<ce<<endl;
break;
}
cout<<"cost = "<<cost<<"\ta = "<<ae<<"\tb = "<<be<<"\tc = "<<ce<<endl;
ae+=dx[0];be+=dx[1];ce+=dx[2];
lastcost=cost;
}
}
|