我对 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")
如何改进它以获取更多信息?
提前致谢
我对 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")
如何改进它以获取更多信息?
提前致谢
您可以修改函数以将传递给它的值存储到全局列表中。
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 语句。
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
管道将输出传输到文本文件,然后进行一些编辑以获取用于绘图的参数值。
如果您想要的只是函数评估的数量,请查看$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 的解决方案或类似的解决方案。