了解R中optim()的maxit参数

时间:2018-12-05 20:53:40

标签: r optimization mathematical-optimization

在下面对optim()的调用中,我期望对fn()进行一次评估,对gr()进行一次评估,因为maxit=1。但是,fn()gr()分别被评估7次。

optim(par=1000, fn=function(x) x^2, gr=function(x) 2*x,
      method="L-BFGS-B", control=list(maxit=1))$counts
function gradient 
       7        7 

这是为什么?是虫子吗?还是为什么optim()对一次迭代进行7次评估?


更详细的输出:

optim(par=1000,
      fn=function(x) { cat("f(", x, ")", sep="", fill=TRUE); x^2 },
      gr=function(x) { cat("g(", x, ")", sep="", fill=TRUE); 2*x },
      method="L-BFGS-B", control=list(maxit=1))$counts
f(1000)
g(1000)
f(999)
g(999)
f(995)
g(995)
f(979)
g(979)
f(915)
g(915)
f(659)
g(659)
f(1.136868e-13)
g(1.136868e-13)
function gradient 
       7        7 

(已通过R版本3.5.0测试。)

3 个答案:

答案 0 :(得分:2)

迭代是优化算法的一次迭代。 功能评估是对目标功能的单次调用。每次迭代需要多少个函数求值取决于:

  • 正在使用什么算法(例如Nelder-Mead与BFGS与...)
  • 一个迭代步骤如何工作
    • 例如用于Nelder-Mead an iteration comprises(1)反射; (2)[也许]扩展; (3)[也许]收缩; (4)[也许]收缩;总会有一个评估(反射),但是其他步骤取决于第一步中发生的情况
    • 对于L-BFGS-B,我认为涉及行搜索...
  • 是否需要通过有限差分计算导数

对于它的价值,nlminb允许单独控制最大迭代次数和最大评估次数:

  

‘eval.max’目标函数的最大评估次数             允许的。默认值为200。
     ‘iter.max’允许的最大迭代次数。默认值为150。

答案 1 :(得分:1)

文档:

有关如何辨别的更多信息,请参见https://stat.ethz.ch/R-manual/R-devel/library/stats/html/optim.html

convergence 
An integer code. 0 indicates successful completion (which is always the case for "SANN" and "Brent"). Possible error codes are

1      indicates that the iteration limit maxit had been reached.

运行您的代码(但看着convergence而不是counts),我得到:

> optim(par=1000,
+       fn=function(x) { cat("f(", x, ")", sep="", fill=TRUE); x^2 },
+       gr=function(x) { cat("g(", x, ")", sep="", fill=TRUE); 2*x },
+       method="L-BFGS-B", control=list(maxit=1))$convergence
f(1000)
g(1000)
f(999)
g(999)
f(995)
g(995)
f(979)
g(979)
f(915)
g(915)
f(659)
g(659)
f(1.136868e-13)
g(1.136868e-13)
[1] 1

因此它进行了一次迭代并停止,返回了convergence = 1。另一个关键字在counts描述中,内容为:

counts  
A two-element integer vector giving the number of calls to fn and gr respectively. 
This excludes those calls needed to compute the Hessian, if requested, and any calls 
to fn to compute a finite-difference approximation to the gradient.

对其进行隐喻调用很多次以找出正在发生的事情。您可以查看c代码,以确定每种方法将调用您的函数多少次。

答案 2 :(得分:0)

在这里您可以找到很好的解释。

https://stat.ethz.ch/pipermail/r-devel/2010-August/058081.html

关键是在迭代过程中多次评估函数。 您可以看到将maxit增加到2会导致另一个函数评估。