Ceres优化器
1、优化器的配置步骤
#include <iostream>
#include<ceres/ceres.h>
using namespace std;
//第一部分 构建costfunction函数
struct CostFunctor
{
//模板函数
template <typename T>
//传入待优化变量和承接残差的变量列表
bool operator()(const T* const x, T* residual) const {
//残差计算步骤
residual[0] = T(0.5)*(T(10.0)-x[0])*(T(10.0)-x[0]);
return true;
}
};
int main(int argc, char** argv)
{
//寻优参数x的初始值,为5
double initial_x = 5.0;
double x = initial_x;
//第二部分 通过代价函数构建带求解的优化问题
//2.1 实例化Problem对象
ceres::Problem problem;
//2.2 使用自动求导函数,将构建好的代价函数结构体传入,第一个1是输出维度,即残差维度;第二个1是输入维度,即待优化变量维度
ceres::CostFunction* costfunction = new ceres::AutoDiffCostFunction<CostFunctor,1,1>(new CostFunctor);
//添加误差项:
//这里分两种情况,不添加核函数的化,默认为:nullptr;如果添加核函数,比如柯西核:new ceres::CauchyLoss(0.5)
problem.AddResidualBlock(costfunction,nullptr,&x);
//第三部分 配置求解器参数,调用Solve方法
ceres::Solver::Options options;
//配置增量方程的解法,此处用QR
options.linear_solver_type = ceres::DENSE_QR;
//是否输出到cout
options.minimizer_progress_to_stdout = true;
//优化信息
ceres::Solver::Summary summary;
//求解: 1、求解器 2、实例化problem 3、优化器
Solve(options,&problem,&summary);
//最终结果
std::cout <<"初始值x: "<<initial_x<<"迭代到->: "<<x<<"\n";
return 0;
}
2、CMakLists.txt文件内容
cmake_minimum_required(VERSION 2.8)
project(TEST_CERES)
#CERES
find_package(Ceres REQUIRED)
include_directories(${CERES_INCLUDE_DIRS})
add_executable(testceres ceres.cpp)
target_link_libraries(testceres ${CERES_LIBRARIES})
3、编译遇到的错误
fatal error: Eigen/Core: 没有那个文件或目录
#include <Eigen/Core> // For Eigen::aligned_allocator
解决办法:
sudo ln -s /usr/include/eigen3/Eigen /usr/include/Eigen
4、柯西核:new ceres::CauchyLoss(0.5)
各个损失函数的趋势图如下:
个人理解:柯西函数的x轴值在0.5前,还是按照?
x轴值大于0.5后,按照?