[英]Passing arguments in nonlinear optimization function `nloptr`
My initial question can be found here: Optimization in R with arbitrary constraints 我的初始问题可以在这里找到: R中的任意约束优化
It led to another question how to pass arguments into nloptr
. 它引发了另一个问题,如何将参数传递给
nloptr
。
I need to minimize a function F(x,y,A)
where x
and y are vectors and A
is a matrix, while having constrains that sum(x * y) >= sum(y/3)
and sum(x)=1
. 我需要最小化函数
F(x,y,A)
,其中x
和y是向量, A
是矩阵,同时约束sum(x * y) >= sum(y/3)
和sum(x)=1
。 I have tried to use nloptr
: 我试过用
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)
And I receive an error: 'A' passed to (...) in 'nloptr' but this is not required in the eval_g_ineq function.
我收到一个错误:
'A' passed to (...) in 'nloptr' but this is not required in the eval_g_ineq function.
If I say nloptr( ... , y, A)
如果我说
nloptr( ... , y, A)
I get: eval_f requires argument 'cov.mat' but this has not been passed to the 'nloptr' function.
我得到:
eval_f requires argument 'cov.mat' but this has not been passed to the 'nloptr' function.
Any advice would be great. 任何建议都会很棒。 Thanks
谢谢
So there are several things going on here: 所以这里有几件事情:
First, the objective function, F
, the equality constraint function, Hc
, and the inequality constraint function, Gc
, all have to take the same arguments. 首先,目标函数
F
,等式约束函数Hc
和不等式约束函数Gc
都必须采用相同的参数。 So pass x, y, A
to all three and just ignore them where they are not needed. 因此,将
x, y, A
传递给所有三个,并在不需要它们的地方忽略它们。
Second, you have to define y
and A
somewhere... 其次,你必须在某处定义
y
和A
......
Third, you must specify which algorithm to use. 第三,您必须指定要使用的算法。 Do this with
opts=list(algoritm=...)
. 使用
opts=list(algoritm=...)
执行此操作。 It turns out that if you are (a) using constraints, and (b) not providing functions to calculate the jacobian matrices, then only some of the algorithms are appropriate. 事实证明,如果你是(a)使用约束,(b) 不提供计算雅可比矩阵的函数,那么只有一些算法是合适的。 In your case
opts=list(algorithm="NLOPT_GN_ISRES")
seems to work. 在你的情况下,
opts=list(algorithm="NLOPT_GN_ISRES")
似乎有效。
Finally, the default maxeval = 100
which turns out to be not nearly enough. 最后,默认的
maxeval = 100
,结果证明还不够。 I had to set it to 100,000 to get convergence. 我不得不将其设置为100,000以获得收敛。
Putting this all together, albeit with a made-up objective function: 把这一切放在一起,虽然有一个弥补的目标函数:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.