代码之家  ›  专栏  ›  技术社区  ›  Ari.stat

用RcppNumerical优化后得到fèu梯度函数中的变量

  •  1
  • Ari.stat  · 技术社区  · 7 年前

    我使用RcppNumerical进行优化,需要在中声明一些变量 f_grad 优化完成后的函数。

    为了解释我的问题,让我们以RcppNumerical包中的标准示例为例。首先,我们需要创建一个类。

    // [[Rcpp::depends(RcppEigen)]]
    // [[Rcpp::depends(RcppNumerical)]]
    
    #include <RcppNumerical.h>
    
    using namespace Numer;
    
    // f = 100 * (x2 - x1^2)^2 + (1 - x1)^2
    // True minimum: x1 = x2 = 1
    class Rosenbrock: public MFuncGrad
    {
    public:
    double f_grad(Constvec& x, Refvec grad)
        {
         double t1 = x[1] - x[0] * x[0];
         double t2 = 1 - x[0];
         grad[0] = -400 * x[0] * t1 - 2 * t2;
         grad[1] = 200 * t1;
         return 100 * t1 * t1 + t2 * t2;
        }
    };
    

    // [[Rcpp::export]]
    Rcpp::List optim_test()
    {
        Eigen::VectorXd x(2);
        x[0] = -1.2;
        x[1] = 1;
        double fopt;
        Rosenbrock f;
        int res = optim_lbfgs(f, x, fopt);
        return Rcpp::List::create(
            Rcpp::Named("xopt") = x,
            Rcpp::Named("fopt") = fopt,
            Rcpp::Named("status") = res
        );
    }
    

    t1 t2

    我的例子可能不太适合我所寻找的,因为它很容易计算 t2级

    1 回复  |  直到 7 年前
        1
  •  1
  •   Ralf Stubner    7 年前

    您可以使用成员变量作为感兴趣的变量。为了简单起见,我使用 public 这里的成员:

    // [[Rcpp::depends(RcppEigen)]]
    // [[Rcpp::depends(RcppNumerical)]]
    
    #include <RcppNumerical.h>
    
    using namespace Numer;
    
    // f = 100 * (x2 - x1^2)^2 + (1 - x1)^2
    // True minimum: x1 = x2 = 1
    class Rosenbrock: public MFuncGrad
    {
    public:
      double t1;
      double t2;
    
      double f_grad(Constvec& x, Refvec grad)
      {
        t1 = x[1] - x[0] * x[0];
        t2 = 1 - x[0];
        grad[0] = -400 * x[0] * t1 - 2 * t2;
        grad[1] = 200 * t1;
        return 100 * t1 * t1 + t2 * t2;
      }
    };
    
    // [[Rcpp::export]]
    Rcpp::List optim_test()
    {
      Eigen::VectorXd x(2);
      x[0] = -1.2;
      x[1] = 1;
      double fopt;
      Rosenbrock f;
      int res = optim_lbfgs(f, x, fopt);
      return Rcpp::List::create(
        Rcpp::Named("xopt") = x,
        Rcpp::Named("fopt") = fopt,
        Rcpp::Named("status") = res,
        Rcpp::Named("t1") = f.t1,
        Rcpp::Named("t2") = f.t2
      );
    }
    
    /*** R
    optim_test()
    */
    

    结果:

    > optim_test()
    $xopt
    [1] 1 1
    
    $fopt
    [1] 3.12499e-15
    
    $status
    [1] 0
    
    $t1
    [1] -2.849634e-09
    
    $t2
    [1] -4.809313e-08
    
    推荐文章