這裏是我的代碼:用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
也許東西函數語法?
謝謝,夥計們:)
只是一個猜測:也許有多個'dP'值等於最大值,在這種情況下,您將返回一個長度大於1的向量。 – Aaron
當函數返回'is.numeric'或'is.integer'爲'FALSE'的值時,DEoptim返回該錯誤。注意'sapply(1:120,besty)'返回一個錯誤。 –
@JoshuaUlrich我已編輯我的帖子,以反映您的提示。 –