【发布时间】:2019-05-18 11:41:05
【问题描述】:
考虑函数fn(),它将最近的输入x 及其返回值ret <- x^2 存储在父环境中。
makeFn <- function(){
xx <- ret <- NA
fn <- function(x){
if(!is.na(xx) && x==xx){
cat("x=", xx, ", ret=", ret, " (memory)", fill=TRUE, sep="")
return(ret)
}
xx <<- x; ret <<- sum(x^2)
cat("x=", xx, ", ret=", ret, " (calculate)", fill=TRUE, sep="")
ret
}
fn
}
fn <- makeFn()
fn() 仅在提供不同输入值时进行计算。否则,它会从父环境中读取ret。
fn(2)
# x=2, ret=4 (calculate)
# [1] 4
fn(3)
# x=3, ret=9 (calculate)
# [1] 9
fn(3)
# x=3, ret=9 (memory)
# [1] 9
当插件fn() 到optim() 中找到其最小值时,会出现以下意外行为结果:
optim(par=10, f=fn, method="L-BFGS-B")
# x=10, ret=100 (calculate)
# x=10.001, ret=100.02 (calculate)
# x=9.999, ret=100.02 (memory)
# $par
# [1] 10
#
# $value
# [1] 100
#
# (...)
这是一个错误吗?怎么会这样?
即使使用 R 的 C-API,我也很难想象这种行为是如何实现的。有什么想法吗?
注意:
-
作品:
library("optimParallel") # (parallel) wrapper to optim(method="L-BFGS-B") cl <- makeCluster(2); setDefaultCluster(cl) optimParallel(par=10, f=fn) -
作品:
optimize(f=fn, interval=c(-10, 10)) -
作品:
optim(par=10, fn=fn) -
失败:
optim(par=10, fn=fn, method="BFGS") -
作品:
library("lbfgs"); library("numDeriv") lbfgs(call_eval=fn, call_grad=function(x) grad(func=fn, x=x), vars=10) -
作品:
library("memoise") fn_mem <- memoise(function(x) x^2) optim(par=10, f=fn_mem, method="L-BFGS-B") 使用 R 版本 3.5.0 测试。
【问题讨论】:
-
我会将示例发送到 R-devel 列表 (stat.ethz.ch/mailman/listinfo/r-devel)
标签: r optimization mathematical-optimization nonlinear-optimization