1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
#include <Eigen/Core>
#include <iostream>
#include <LBFGS.h>
using Eigen::VectorXf;
using Eigen::MatrixXf;
using namespace LBFGSpp;
class Rosenbrock
{
private:
int n;
public:
Rosenbrock(int n_) : n(n_) {}
float operator()(const VectorXf& x, VectorXf& grad)
{
float fx = 0.0;
for(int i = 0; i < n; i += 2)
{
float t1 = 1.0 - x[i];
float t2 = 10 * (x[i + 1] - x[i] * x[i]);
grad[i + 1] = 20 * t2;
grad[i] = -2.0 * (x[i] * grad[i + 1] + t1);
fx += t1 * t1 + t2 * t2;
}
return fx;
}
};
int main()
{
const int n = 10;
LBFGSParam<float> param;
LBFGSSolver<float> solver(param);
Rosenbrock fun(n);
VectorXf x = VectorXf::Zero(n);
float fx;
int niter = solver.minimize(fun, x, fx);
std::cout << niter << " iterations" << std::endl;
std::cout << "x = \n" << x.transpose() << std::endl;
std::cout << "f(x) = " << fx << std::endl;
std::cout << "grad = " << solver.final_grad().transpose() << std::endl;
std::cout << "||grad|| = " << solver.final_grad_norm() << std::endl;
std::cout << "approx_hess = \n" << solver.final_approx_hessian() << std::endl;
std::cout << "approx_inv_hess = \n" << solver.final_approx_inverse_hessian() << std::endl;
return 0;
}
|