我想使用一些R函数来优化多个约束下的给定函数。
# P, z assumed to be arrays of length m^2
# (P is actually a m x m matrix but it seems that only vectors are accepted within the optimizer)
# t1, t2 are constants
eval_f <- function(P,z,t1,t2){
tmp_sum <- 0
m <- length(z)
for(i in 1:m){
tmp_sum <- tmp_sum + P[i]*(abs(t2*z[m-i+1] - t1*z[i])^3)
}
eval_f <- tmp_sum
}
# Let's further assume the following constraints
# Convert P into a matrix, row sums of P shall sum up to 1 (probabilities),
# i.e. the result f_constr_1 should be equal to a zero vector
# of length m
f_constr_1 <- function(P){
len <- sqrt(length(P))
P <- matrix(P,len,len)
f_constr_1 <- rowSums(P) - rep(1,ncol(P))
}
# The second constraint forces the values of P to be between 0 and 1
lb <- rep(0,m*m)
ub <- rep(1,m*m)
这是我到目前为止所得到的。现在我正在努力解决以下问题。
什么优化器可以解决这个问题?我首先开始使用以下内容:
m <- 4
P <- rep(0.25,m*m)
z <- rep(c(-1.15,-0.32,0.32,1.15),m)
nloptr(P,eval_f,lb=lb,ub=ub,z=z,t1=0.25,t2=0.5,opts=list("algorithm" = "NLOPT_GN_DIRECT"))
从技术角度来看,这有效......但是现在我想实现约束,突然间我收到以下错误消息。
nloptr(P,eval_f,f_constr_1,lb=lb,ub=ub,z=z,t1=0.25,t2=0.5,opts=list("algorithm" = "NLOPT_GN_DIRECT"))
> Unused arguments (z = c(-1.15, -0.32, 0.32, 1.15, -1.15, -0.32, 0.32, 1.15, -1.15, -0.32, 0.32, 1.15, -1.15, -0.32, 0.32, 1.15), t1 = 0.25, t2 = 0.5)
所以基本上有三个问题......
感谢您的帮助!
编辑1:有关“未使用的参数”的问题可以通过重写约束函数来解决。
f_constr_1 <- function(P,z,t1,t2){
len <- sqrt(length(P))
P <- matrix(P,len,len)
f_constr_1 <- rowSums(P) - rep(1,ncol(P))
}