一、非线性最小二乘
minx12∑iρi(||fi(xi1,...,xik)||2)s.t.lj≤xj≤uj
m
i
n
x
1
2
∑
i
ρ
i
(
|
|
f
i
(
x
i
1
,
.
.
.
,
x
i
k
)
|
|
2
)
s
.
t
.
l
j
≤
x
j
≤
u
j
1、ParameterBlock -> 参数块:例如R、T 构成相机位姿参数块,也可以是单一参数
2、CostFunction -> 代价函数:依赖参数块,如 fi(i) f i ( i )
3、ResidualBlock -> 残差块:如
ρi(||fi(xi1,...,xik)||2)
ρ
i
(
|
|
f
i
(
x
i
1
,
.
.
.
,
x
i
k
)
|
|
2
)
4、LossFunction -> 损失函数:如 ρi ρ i
【NOTE】
【例1】
f(x)=10−x
f
(
x
)
=
10
−
x
- 1、定义代价函数:
struct CostFunctor {
template <typename T>
bool operator() (const T* const x, T* residual) const {
residual[0] = T(10.0) - x[0];
return true;
}
}
【NOTE】
- 非静态成员函数后加const,表示隐含传入的this指针为const,即不允许在成员函数内修改成员变量。
- 目的是为了定义、计算残差
- 这是一个线性问题
2、构造Ceres
google::InitGoogleLogging(argv[0]);
// 初始值
double inital_x = 5.0;
double x = initial_x;
Problem problem;
// 采用自动微分求导
CostFunction* cost_function = new AutoDiffCostFunction<CostFunctor, 1, 1>(new CostFunctor);
// 第一个参数指的是每个残差的维数,第二个参数开始是参数的维数
problem.AddResidualBlock(cost_function, NULL, &x);
Solver::Options options;
...
Solver::Summary summary;
Solver(options, &problem, &summary);
5、导数类型
- Numeric Derivatives
- 例如:residual[0] = 10.0 - x[0]
- Analytic Derivatives
- 继承CostFunction/SizedCostFunction
class QuadraticCostFunction:public ceres::SizedCostFunction<1,1> {
public:
vitrual ~QuadraticCostFunction() {}
virtual bool Evaluate(double const* const* parameters, double* residuals, double ** jacobians) const {
const double x = parameters[0][0];
residuals[0] = 10 - x;
if (jacobians != NULL && jacobians[0] != NULL) {
jacobians[0][0] = -1;
}
return true;
}
}
- 【NOTE】
- input:parameters
- output:residuals jacobians
6、Powell’s Function
f1(x)=x1+10x2f2(x)=5–√(x3−x4)f3(x)=(x2−2x3)2f4(x)=10−−√(x1−x4)2F(x)=[f1(x),f2(x),f3(x),f4(x)]
f
1
(
x
)
=
x
1
+
10
x
2
f
2
(
x
)
=
5
(
x
3
−
x
4
)
f
3
(
x
)
=
(
x
2
−
2
x
3
)
2
f
4
(
x
)
=
10
(
x
1
−
x
4
)
2
F
(
x
)
=
[
f
1
(
x
)
,
f
2
(
x
)
,
f
3
(
x
)
,
f
4
(
x
)
]
=> find x such that 12||F(x)||2 1 2 | | F ( x ) | | 2 is minimized
=> 思路:与例1类似,但是需要构造多个代价函数,然后AddResidualBlock