用Ceres解决最小二乘问题

该代码源于《视觉SLAM十四讲》 ceres_curve_fitting/main.cpp

Ceres库用于通用的最小二乘问题求解;我们需要做的就是定义优化问题,设置选项,输入近Ceres求解即可。

该页代码用于日后查找方便 (添加了部分笔记)、
问题描述
该代码主要是求解曲线 y= exp(a*x*x + b*x +c) + w;(w是噪声) 假设有N个x和y的观测数据点,用来求解曲线的参数。则待估计变量实际上是a,b,c
解决思路
先用CV随机数产生器生成N个数据(包括噪声) 构造最小二乘问题 ; 配置求解器(配置项比较多), 对问题进行优化。
代码部分

#include 
#include 
#include 
#include 

using namespace std;

// 代价函数的计算模型(不是很熟悉这种模型定义)
struct CURVE_FITTING_COST
{
    CURVE_FITTING_COST ( double x, double y ) : _x ( x ), _y ( y ) {}
    // 残差的计算
    template <typename T> //这个是定义模板的固定格式
    bool operator() (
        const T* const abc,     // 模型参数,有3维
        T* residual ) const     // 残差
    {
        residual[0] = T ( _y ) - ceres::exp ( abc[0]*T ( _x ) *T ( _x ) + abc[1]*T ( _x ) + abc[2] ); // y-exp(ax^2+bx+c)
        return true;
    }
    const double _x, _y;    // x,y数据
};

int main ( int argc, char** argv )
{
    double a=1.0, b=2.0, c=1.0;         // 真实参数值
    int N=100;                          // 数据点
    double w_sigma=1.0;                 // 噪声Sigma值
    cv::RNG rng;                        // OpenCV随机数产生器
    double abc[3] = {0,0,0};            // abc参数的估计值

    vector<double> x_data, y_data;      // 数据

    cout<<"generating data: "<for ( int i=0; idouble x = i/100.0;
        x_data.push_back ( x );
        y_data.push_back (
            exp ( a*x*x + b*x + c ) + rng.gaussian ( w_sigma )
        );
        cout<" "<// 构建最小二乘问题
    ceres::Problem problem;
    for ( int i=0; i// 向问题中添加误差项
        // 使用自动求导,模板参数:误差类型,输出维度,输入维度,维数要与前面struct中一致
            new ceres::AutoDiffCostFunction1, 3> ( 
                new CURVE_FITTING_COST ( x_data[i], y_data[i] )
            ),
            nullptr,            // 核函数,这里不使用,为空
            abc                 // 待估计参数
        );
    }

    // 配置求解器
    ceres::Solver::Options options;     // 这里有很多配置项可以填
    options.linear_solver_type = ceres::DENSE_QR;  // 增量方程如何求解
    options.minimizer_progress_to_stdout = true;   // 输出到cout

    ceres::Solver::Summary summary;                // 优化信息
    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();
    ceres::Solve ( options, &problem, &summary );  // 开始优化
    chrono::steady_clock::time_point t2 = chrono::steady_clock::now();
    chrono::duration<double> time_used = chrono::duration_castdouble>>( t2-t1 );
    cout<<"solve time cost = "<" seconds. "<// 输出结果
    cout<cout<<"estimated a,b,c = ";
    for ( auto a:abc ) cout<" ";
    cout<return 0;
}

你可能感兴趣的:(C++11,代码)