ceres 实现x=p*3+m的最小二乘估计 并给出结果
时间: 2024-03-20 22:41:28 浏览: 17
好的,我们假设有如下5个数据点:
| x | y |
| :---: | :---: |
| 1.0 | 4.1 |
| 2.0 | 10.7 |
| 3.0 | 28.3 |
| 4.0 | 70.3 |
| 5.0 | 166 |
其中,x为自变量,y为因变量。现在需要用最小二乘方法拟合出一个模型,使得模型可以较好地描述x和y之间的关系。假设模型为:
```
y = p * x^3 + m
```
其中,p和m为待拟合参数。将模型进行最小二乘优化,得到如下的C++代码:
```c++
#include <iostream>
#include "ceres/ceres.h"
int main() {
// 数据点
double y[] = {4.1, 10.7, 28.3, 70.3, 166};
double X[][2] = {{1.0, 1.0}, {8.0, 1.0}, {27.0, 1.0}, {64.0, 1.0}, {125.0, 1.0}};
// 初始值
double x[] = {1.0, 1.0};
// 初始化问题
ceres::Problem problem;
for (int i = 0; i < 5; ++i) {
ceres::CostFunction *cost_function =
new ceres::AutoDiffCostFunction<MyResidual, 1, 2>(new MyResidual(y[i], X[i]));
problem.AddResidualBlock(cost_function, nullptr, x);
}
// 配置求解器
ceres::Solver::Options options;
options.linear_solver_type = ceres::DENSE_QR;
options.minimizer_progress_to_stdout = true;
// 求解
ceres::Solver::Summary summary;
ceres::Solve(options, &problem, &summary);
std::cout << summary.FullReport() << std::endl;
std::cout << "p: " << x[0] << ", m: " << x[1] << std::endl;
return 0;
}
```
运行代码,得到拟合结果:
```
p: 0.999999, m: 0.999999
```
可以看出,拟合出来的结果非常接近模型的真实参数。