优化 - 将目标和梯度函数参数作为列表传递 [英] optimization - Passing objective and gradient function arguments as list

查看:55
本文介绍了优化 - 将目标和梯度函数参数作为列表传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数可以同时评估梯度和输出.我想针对目标函数对其进行优化.如何将目标和梯度作为列表传递给 optimx?下面的例子说明了这个问题:

I have a function that evaluates the gradient and output simultaneously. I want to optimize it with respect to an objective function. How do I pass the objective and gradient as a list to optimx? The example below illustrates the problem:

假设我想找到多项式 x^4 - 3*x^2 + 2*x + 3 的最小非负根.它的梯度是4*x^3 - 6*x + 2.我在optimx中使用了nlminb方法,如下图.

Suppose I want to find the smallest non-negative root of the polynomial x^4 - 3*x^2 + 2*x + 3. Its gradient is 4*x^3 - 6*x + 2. I use the method nlminb in optimx, as shown below.

optimx(par = 100, method = "nlminb", fn = function(x) x^4 - 3*x^2 + 2*x + 3, 
                                     gr=function(x) 4*x^3 - 6*x + 2, lower = 0)

这很好用,我得到以下输出:

This works fine, and I get the following output:

       p1 value fevals gevals niter convcode kkt1 kkt2 xtimes
nlminb  1     3     27     24    23        0 TRUE TRUE      0

现在假设我定义了函数 fngr,它以列表的形式返回目标和梯度:

Now suppose I define the function fngr, which returns both the objective and gradient as a list:

fngr <- function(x) {
  fn <- x^4 - 3*x^2 + 2*x + 3
  gr <- 4*x^3 - 6*x + 2
  return (list(fn = fn, gr = gr))
}

我尝试按如下方式调用 optimx:

I tried to call optimx as follows:

do.call(optimx, c(list(par = 100, lower = 0, method="nlminb"), fngr))

这返回了以下错误:

Error in optimx.check(par, optcfg$ufn, optcfg$ugr, optcfg$uhess, lower,  : 
  Function provided is not returning a scalar number

当我想将目标和梯度作为列表传递时,定义 fngr 和调用 optimx 的正确方法是什么?

What is the right way to define fngr and the call to optimx when I want to pass the objective and gradient as a list?

谢谢.

推荐答案

定义一个无参数函数,它可以用合适的名字传递两个函数......当被调用时:

Define a parameter-less function which can deliver the two functions with suitable names ... when called:

> fngr <- function() {
+   fn <- function(x) {x^4 - 3*x^2 + 2*x + 3}
+   gr <- function(x) {4*x^3 - 6*x + 2}
+   return (list(fn = fn, gr = gr))
+ }
> do.call(optimx, c(list(par = 100, lower = 0, method="nlminb"), fngr() ))
                                    notice the need to call it ------^^
       p1 value fevals gevals niter convcode kkt1 kkt2 xtimes
nlminb  1     3     27     24    23        0 TRUE TRUE  0.002

5 年后看到这个,我可以完全理解这种困惑.@ user3294195 的做法更为典型.这不是 R 中传递函数对象的典型方式.

Looking at this 5 years later I can fully understand the confusion. The way that @ user3294195 did it was much more typical. This is not a typical way of passing function objects in R.

这篇关于优化 - 将目标和梯度函数参数作为列表传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆