5

我最初的问题可以在这里找到:任意约束的 R 优化

它导致了另一个问题,如何将参数传递到nloptr.
我需要最小化一个函数F(x,y,A),其中x和 y 是向量并且A是矩阵,同时约束sum(x * y) >= sum(y/3)sum(x)=1。我试过使用nloptr

F <- function(x,y,A){
   ...
}

Gc <- function(x,y){
  return(sum(y/3) - sum(x*y))
} 

Hc <- function(x){
  retunr(1-sum(x))
}

nloptr(x0=rep(1/3,3), eval_f=F, lb = 0.05, ub = 1, eval_g_ineq = Gc, eval_g_eq = Hc, opts = list(), y=y, A=A)

我收到一个错误: 'A' passed to (...) in 'nloptr' but this is not required in the eval_g_ineq function.

如果我说nloptr( ... , y, A)

我得到:eval_f requires argument 'cov.mat' but this has not been passed to the 'nloptr' function.

任何建议都会很棒。谢谢

4

1 回答 1

7

所以这里发生了几件事:

首先,目标函数 、F等式约束函数Hc和不等式约束函数Gc都必须采用相同的参数。所以传递x, y, A给所有三个,并在不需要它们的地方忽略它们。

其次,您必须在某个地方定义y...A

第三,您必须指定要使用的算法。用opts=list(algoritm=...). 事实证明,如果您 (a) 使用约束,并且 (b)提供计算雅可比矩阵的函数,那么只有一些算法是合适的。在你的情况下opts=list(algorithm="NLOPT_GN_ISRES")似乎有效。

最后,maxeval = 100事实证明默认值还不够。我必须将其设置为 100,000 才能收敛。

把这一切放在一起,尽管有一个虚构的目标函数:

F <- function(x,y,A){  # made-up function
  # minimize scaled distance between points x and y
  sum((A[1]*x-A[2]*y)^2)
}
Gc <- function(x,y,A) return(sum(y/3) - sum(x*y))
Hc <- function(x,y,A) return(1-sum(x))

library(nloptr)
y= c(0,1,0)
A= c(10,1)
opt <- nloptr(x0=rep(1/3,3), eval_f=F, lb = rep(0.05,3), ub = rep(1,3), 
              eval_g_ineq = Gc, eval_g_eq = Hc, 
              opts = list(algorithm="NLOPT_GN_ISRES",maxeval=100000), y=y, A=A)
opt$solution
# [1] 0.2990463 0.4004237 0.3005300
于 2014-02-07T22:13:50.283 回答