查看memoise 包。为了更详细地解释,请考虑如何在 R 中针对知道导数的函数进行优化的简单示例:
complex.function <- function(x){
Sys.sleep(3)
}
f <- function(x){
cat("f",x,"\n")
complex.function(x)
(x-1)^4+(x-1)^2+7
}
g <- function(x){
cat("g",x,"\n")
complex.function(x)
4*(x-1)^3+2*(x-1)
}
system.time(optim(3.1, f, g,method="BFGS")) ##57.01sec
#f 3.1
#g 3.1
#f -38.144
#f -5.1488
#f 1.45024
#g 1.45024
#f 1.398015
#g 1.398015
#f 1.146116
#g 1.146116
#f 0.8414061
#f 1.085174
#g 1.085174
#f 1.00532
#g 1.00532
#f 1.000081
#g 1.000081
#f 0.9999192
#f 1.000048
因为该方法在几乎相同的点上评估 f 和 g,所以有优化的潜力。
现在,如果您 memoise() 包含复杂计算的函数,它会缓存输出,因此您可以执行以下操作:
library(memoise)
complex.function2 <- memoise(function(x){
Sys.sleep(3)
list(fun=(x-1)^4+(x-1)^2+7,deriv=4*(x-1)^3+2*(x-1))
})
f2 <- function(x){
cat("f2",x,"\n")
complex.function2(x)$fun
}
g2 <- function(x){
cat("g2",x,"\n")
complex.function2(x)$deriv
}
system.time(optim(3.1, f2, g2,method="BFGS")) ##36.02sec
并减少调用复杂函数的次数,因此我的计算机上的执行时间从 57 秒下降到 36 秒。
查看optim 的帮助文件,看看您感兴趣的方法是否实际使用了衍生物 - 如果不是,这一切都没有实际意义。