从R的optim函数获取更多详细信息 [英] Getting more details from optim function from R

查看:109
本文介绍了从R的optim函数获取更多详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm not very familiar with the optim function, and I wanted to get these informations from its results: a) how many iterations were needed for achieving the result? and b) to plot the sequence of partial solutions, that is, the solution obtained in the end of each iteration.

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

My code until now looks like this:

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

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

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

How can I improve it to get further information?

预先感谢

推荐答案

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

You could modify your function to store the values that are passed into it into a global list.

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和val,可以看到发生了什么.如果您想在optim运行时查看这些值,则也向该函数中添加一条print语句.

Now if you examine i and vals after you run the function you can see what happened. If you want to see the values while optim is running throw a print statement into the function as well.

这篇关于从R的optim函数获取更多详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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