紧接上次的手写高斯牛顿,今天顺便将LM算法也进行了手写实现,并且自己基于eigen的高斯牛顿进行了对比,可以很明显的看到,LM的算法收敛更快,精度也略胜一筹,这次高博的书不够用了,参考网上伪代码进行实现.同学们有什么问题都可以讨论,理论部分的细节后面会补上,最近确实有点忙.
伪代码
程序源码
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Dense>
#include"opencv2/opencv.hpp"
#include"opencv4/opencv2/opencv.hpp"
#include<iostream>
#include<vector>
using namespace Eigen;
using namespace std;
using namespace cv;
//生成测试数据
void makeTheTestNum(vector<double> &xSet ,vector<double> &ySet);
//LM算法结算
void LM(const vector<double> &xSet ,const vector<double> &ySet ,double &a,double &b,double &c);
void makeTheTestNum(vector<double> &xSet ,vector<double> &ySet){
RNG rng;
double noise = rng.gaussian(1);
//设定值
double a = 2;
double b = 1;
double c = 1;
for(int i = 0;i <100;i++)
{
double x = i/100.0;//注意这个.0,不然出来全是0
double fx = exp(a*x*x + b*x + c)+noise;
xSet.push_back(x);
ySet.push_back(fx);
}
cout<<xSet.size()<<endl;
if(xSet.size() != ySet.size())
cout<<"data is bad!"<<endl;
}
void LM(const vector<double> &xSet ,const vector<double> &ySet ,double &a,double &b,double &c){
bool flag = 0;
double cost =0.0;
double lastcost = 0.0;
int maxtimes = 1000;
double v = 2;