这是我的代码:用DEoptim
算法优化的函数;这个功能确实很简单。
可重现的代码:
library(DEoptim)
library(sm)
tau.0 <- c(58.54620, 61.60164, 64.65708, 71.19507, 82.39836, 101.28953, 119.68789)
rate <- c(0.04594674, 0.01679026, 0.02706263, 0.04182605, 0.03753949, 0.04740187, 0.05235710)
Du <- c(4.27157210, -0.07481174, -0.10551229, 0.51753843, 1.51075420, 6.51483315, 7.35631500)
Co <- c(0.2364985, -6.2947479, -7.5422644, -1.2745887, -42.6203118, 55.7663196, 70.9541141)
h <- h.select(x = tau.0, y = rate, method = 'cv')
sm <- sm.regression(x = tau.0, y = rate, h = h)
ya <- sm$estimate
xa <- sm$eval.points
y <- approx(x = xa, y = ya, xout = tau.0, rule = 2)$y
besty <- function(x) {
dtau.0 <- x
xout <- seq(1, max(tau.0), dtau.0)
ratem <- approx(x = tau.0, y = rate / 1, xout = xout)$y
ym <- approx(x = tau.0, y = y / 1, xout = xout)$y
Dum <- approx(x = tau.0, y = Du, xout = xout)$y
Com <- approx(x = tau.0, y = Co, xout = xout)$y
dy <- NULL
for(i in 1:length(ym)) {
dy[i] <- ratem[i] - ym[i-1]
}
dy[is.na(dy)] <- na.omit(dy)[1]
Dum[is.na(Dum)] <- na.omit(Dum)[1]
Com[is.na(Com)] <- na.omit(Com)[1]
dP <- Dum * dy - .5 * Com * dy ^ 2
xout.m <- xout / 12
dcurve <- cbind(dP * 100, xout.m)
PVBP <- dcurve[which(dP == max(dP)),1]
Maty <- dcurve[which(dP == max(dP)),2]
return(- PVBP / x)
}
DEoptim(fn = besty, lower = 1, upper = 120)
对我来说最后一个命令返回
ERROR: unsupported objective function return value
我的代码DEoptim
在优化方面有什么问题?
如果我替换最后一个函数的命令行
return(- PVBP / x)
和
return(as.numeric(- PVBP / x))
它似乎DEoptim
工作正常,直到几次迭代,然后......
> DEoptim(fn = besty, lower = 1, upper = 12)
Iteration: 1 bestvalit: -0.898391 bestmemit: 1.186242
Iteration: 2 bestvalit: -0.903304 bestmemit: 1.185117
Iteration: 3 bestvalit: -0.999273 bestmemit: 1.043355
Iteration: 4 bestvalit: -0.999273 bestmemit: 1.043355
Error in DEoptim(fn = besty, lower = 1, upper = 12) :
unsupported objective function return value
也许是函数语法?
多谢你们 :)