【问题标题】:Getting more details from optim function from R从 R 的 optim 函数中获取更多详细信息
【发布时间】:2014-05-31 22:40:36
【问题描述】:

我对 optim 函数不是很熟悉,我想从它的结果中获取这些信息:a) 需要多少次迭代才能获得结果? b) 绘制部分解的序列,即每次迭代结束时得到的解。

到目前为止,我的代码如下所示:

  f1 <- function(x) {
  x1 <- x[1]
  x2 <- x[2]
  x1^2 + 3*x2^2
}

res <- optim(c(1,1), f1, method="CG")

如何改进它以获得更多信息?

提前致谢

【问题讨论】:

    标签: r artificial-intelligence convex-optimization


    【解决方案1】:

    您可以修改您的函数以将传递给它的值存储到一个全局列表中。

    i <- 0  
    vals <- list()
    f1 <- function(x) {
      i <<- i+1
      vals[[i]] <<- x
    
      x1 <- x[1]
      x2 <- x[2]
      x1^2 + 3*x2^2  
    }
    
    res <- optim(c(1,1), f1, method="CG")
    

    现在,如果您在运行函数后检查 i 和 vals,您可以看到发生了什么。如果你想在 optim 运行时查看值,也可以在函数中添加一个 print 语句。

    【讨论】:

    • 函数式编程中一个很好的练习是编写一个函数,该函数接受一个函数作为参数,并返回一个与该参数函数相同但将日志记录到全局的函数。然后,您可以通过包装而不是更改它来将日志记录添加到传递给 optim 的任何函数!
    • 拥有所有这些可能性真是太好了,但我认为这个最适合我的情况。非常感谢,伙计们!
    【解决方案2】:

    trace=1 作为控制参数传递给optim 可为您提供有关优化进度的更详细信息:

    res <- optim(c(1,1), f1, method="CG", control=list(trace=1))
    # Conjugate gradients function minimizer
    # Method: Fletcher Reeves
    # tolerance used in gradient test=3.63798e-12
    # 0 1 4.000000
    # parameters    1.00000    1.00000 
    # * i> 1 4 0.480000
    # parameters    0.60000   -0.20000 
    #   i> 2 6 0.031667
    # ......
    # * i> 13 34 0.000000
    # parameters   -0.00000    0.00000 
    # 14 34 0.000000
    # parameters   -0.00000    0.00000 
    # Exiting from conjugate gradients minimizer
    #   34 function evaluations used
    #   15 gradient evaluations used
    

    但是,信息似乎只写入标准输出,因此您必须使用sink 将输出通过管道传输到文本文件,然后进行一些编辑以获取用于绘图的参数值。

    【讨论】:

      【解决方案3】:

      如果您想要的只是函数评估的次数,请查看结果的 $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.
      

      对于部分解决方案,您需要@Dason 的解决方案或类似的解决方案。

      【讨论】:

      • +1,但我想知道counts 与实际迭代次数之间的关系。假设我设置了最大迭代次数maxit = 10,但我可以将fncounts 设置为20。我们应该如何解释这个?
      • (嗯,我以为我评论了,但也许它丢失了)。取决于方法和细节:例如,根据局部几何,Nelder-Mead 每次迭代可以采用不同数量(我认为是 2-3)的函数评估。例如试试example("optim"); optim(c(-1.2,1), fr, method = "Nelder-Mead",control=list(trace=100))
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多