R optim - 从单个迭代中检索值

时间:2015-11-08 22:26:45

标签: r optimization

很抱歉可能重复提到的问题。

我想在optim函数的不同迭代中重新计算优化参数的值。目的是检查验证数据集上的错误收敛。

我的问题与this question密切相关,我试图在其中实现我应该解决我的问题的代码。但是,i$count的值都表明优化函数的调用次数比maxit参数中指定的次数多得多:

vals <- list()
f1 <- function(x) {
  i <<- i+1
  vals[[i]] <<- x

  x1 <- x[1]
  x2 <- x[2]
  x1^2 + 3*x2^2  
}

# countBFGS 
i <- 0  
optim(c(1,1), f1, method="BFGS",control = list(trace=1, maxit = 10))$count
i
# countCG 
i <- 0 
optim(c(1,1), f1, method="CG",control = list(trace=1, maxit = 10))$count
i
# countSANN
i <- 0 
optim(c(1,1), f1, method="SANN",control = list(trace=1, maxit = 10))$count
i

有关如何即时捕获优化参数的任何建议吗?

1 个答案:

答案 0 :(得分:4)

观察到的计数差异是由于还会调用目标函数来计算数值导数。如果我们提供衍生品,那么不会发生,并且计数和i将对应。在下面的示例中,它们都是24:

vals <- NULL; i <- 0
gr1 <- function(x) c(2, 6) * x  # gradient
optim(c(1, 1), f1, gr1, method = "BFGS", control = list(trace = 1))$count

## initial  value 4.000000 
## final  value 0.000000 
## converged
## function gradient 
##       24        9 

i
## [1] 24

此外,如果我们使用首先不使用衍生物的优化方法,例如Nelder Mead,那么count和i也将对应。试试这个:

vals <- NULL; i <- 0
optim(c(1, 1), f1, method = "Nelder", control = list(trace = 1))$count
i

已添加:如果使用maxit,请尝试跟踪f1gr1功能。 gr1的评估时间为maxit次,每次f1评估之前gr1的最后一次评估可用于监控f1

vals <- NULL; i <- 0
gr1 <- function(x) c(2, 6) * x  # gradient
trace(gr1, exit = quote(print(c(returnValue(), x))))
trace(f1, exit = quote(print(c(i, returnValue(), x))))
optim(c(1, 1), f1, gr1, method = "BFGS", control = list(trace = 10, maxit = 5))$count
untrace(f1)
untrace(gr1)

,并提供:

Tracing fn(par, ...) on exit 
[1] 1 4 1 1
initial  value 4.000000 
Tracing gr(par, ...) on exit 
[1] 2 6 1 1
Tracing fn(par, ...) on exit 
[1]  2 76 -1 -5
Tracing fn(par, ...) on exit 
[1]  3.00  0.48  0.60 -0.20
Tracing gr(par, ...) on exit 
[1]  1.2 -1.2  0.6 -0.2
Tracing fn(par, ...) on exit 
[1]  4.00000000  0.55976676 -0.73469388  0.08163265
Tracing fn(par, ...) on exit 
[1]  5.0000000  0.1728560  0.3330612 -0.1436735
Tracing gr(par, ...) on exit 
[1]  0.6661224 -0.8620408  0.3330612 -0.1436735
Tracing fn(par, ...) on exit 
[1] 6.000000e+00 1.207714e-05 1.192941e-03 1.884501e-03
Tracing gr(par, ...) on exit 
[1] 0.002385882 0.011307005 0.001192941 0.001884501
Tracing fn(par, ...) on exit 
[1]  7.000000e+00  7.788526e-09 -5.338595e-05 -4.057284e-05
Tracing gr(par, ...) on exit 
[1] -1.067719e-04 -2.434371e-04 -5.338595e-05 -4.057284e-05
final  value 0.000000 
stopped after 5 iterations
function gradient 
       7        5