参考官网​​教程:http://www.ceres-solver.org/nnls_tutorial.htl

Numeric Derivatives

有的时候当自动求导不方便的时候,需要进行数值求导。

构造一个代价函数,应注意和上个例子的区别:

struct NumericDiffCostFunctor {
  bool operator()(const double* const x, double* residual) const {
    residual[0] = 10.0 - x[0];
    return true;
  }
};

添加问题:

CostFunction* cost_function =
  new NumericDiffCostFunction<NumericDiffCostFunctor, ceres::CENTRAL, 1, 1>(
      new NumericDiffCostFunctor);

problem.AddResidualBlock(cost_function, NULL, &x);

注意和自动求导的区别,其代码如下:

CostFunction* cost_function =
    new AutoDiffCostFunction<CostFunctor, 1, 1>(new CostFunctor);

problem.AddResidualBlock(cost_function, NULL, &x);

数值求导在构造函数上区别不大,主要区别在地方使用不同颜色标注了。

完整的程序如下:

#include "ceres/ceres.h"
#include "glog/logging.h"
using ceres::NumericDiffCostFunction;
using ceres::CENTRAL;
using ceres::CostFunction;
using ceres::Problem;
using ceres::Solver;
using ceres::Solve;
// A cost functor that implements the residual r = 10 - x.
struct CostFunctor {
  bool operator()(const double* const x, double* residual) const {
    residual[0] = 10.0 - x[0];
    return true;
  }
};
int main(int argc, char** argv) {
  google::InitGoogleLogging(argv[0]);
  // The variable to solve for with its initial value. It will be
  // mutated in place by the solver.

  double x = 0.5;
  const double initial_x = x;
  // Build the problem.
  Problem problem;
  // Set up the only cost function (also known as residual). This uses
  // numeric differentiation to obtain the derivative (jacobian).

  CostFunction* cost_function =
      new NumericDiffCostFunction<CostFunctor, CENTRAL, 1, 1> (new CostFunctor);
  problem.AddResidualBlock(cost_function, NULL, &x);

  // Run the solver!
  Solver::Options options;
  options.minimizer_progress_to_stdout = true;
  Solver::Summary summary;
  Solve(options, &problem, &summary);
  std::cout << summary.BriefReport() << "\n";
  std::cout << "x : " << initial_x
            << " -> " << x << "\n";
  return 0;

}

CMakeLists.txt文件如下:

cmake_minimum_required(VERSION 2.8)
project(ceres)
#set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake_modules)
find_package(Ceres REQUIRED)
include_directories(${CERES_INCLUDE_DIRS})
add_executable(use_ceres main.cpp)

target_link_libraries(use_ceres ${CERES_LIBRARIES})

运行结果:

非线性优化库Ceres的使用3

相关文章:

  • 2021-07-20
  • 2021-06-13
  • 2021-04-27
  • 2021-10-11
  • 2021-06-21
  • 2021-07-15
  • 2021-07-23
  • 2022-02-02
猜你喜欢
  • 2021-11-22
  • 2022-12-23
  • 2022-12-23
  • 2021-07-01
  • 2021-10-12
  • 2021-06-29
相关资源
相似解决方案