Ceres solver2

本文探讨了在优化问题中使用的两种微分方法:数值微分和解析微分。介绍了这两种方法的应用场景及其优缺点,并提供了具体的代码示例。对于难以实现自动微分的情况,解析微分提供了一种有效解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数值微分和解析微分

数值微分

在某些情况下,很难定义一个模板类cost functor,这种情况下可以用数值微分。例如f(x)=10x

struct CostFunctor {
  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, 1>(
      new NumericDiffCostFunctor)
problem.AddResidualBlock(cost_function, NULL, &x);

通常更推荐使用automatic differentiation,因为它更高效,而数值微分存在数值误差,可能导致收敛速度变慢。

解析微分

在某些情况下,使用自动微分是不太可能的。自动微分依赖于链式求导法则,使用解析微分可以更高效。这种情况下,自己定义函数计算残差和雅可比矩阵更加合适。
同样以f(x)=10x为例

class QuadraticCostFunction : public ceres::SizedCostFunction<1, 1> {
 public:
  virtual ~QuadraticCostFunction() {}
  virtual bool Evaluate(double const* const* parameters,
                        double* residuals,
                        double** jacobians) const {
    const double x = parameters[0][0];
    residuals[0] = 10 - x;

    // Compute the Jacobian if asked for.
    if (jacobians != NULL && jacobians[0] != NULL) {
      jacobians[0][0] = -1;
    }
    return true;
  }
};
More About Derivatives

除了以上方法外,ceres solver还有其他函数,参考DynamicAutoDiffCostFunction, CostFunctionToFunctor, NumericDiffFunctorConditionedCostFunction

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值