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

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

问题描述

我有一个可以同时评估梯度并输出的函数.我想针对目标函数对其进行优化.如何将物镜和渐变作为列表传递给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 below example 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 ... 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

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

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