在非线性优化函数`nloptr`中传递参数 [英] Passing arguments in nonlinear optimization function `nloptr`

查看:520
本文介绍了在非线性优化函数`nloptr`中传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My initial question can be found here:Optimization in R with arbitrary constraints

这引发了另一个问题,如何将参数传递到nloptr.
我需要最小化函数F(x,y,A),其中x和y是向量,而A是矩阵,同时具有sum(x * y) >= sum(y/3)sum(x)=1的约束. 我尝试使用nloptr:

It led to another question how to pass arguments into 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. I have tried to use 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.

任何建议都会很棒.谢谢

Any advice would be great. Thanks

推荐答案

所以这里发生了几件事:

So there are several things going on here:

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

First, the objective function, F, the equality constraint function, Hc, and the inequality constraint function, Gc, all have to take the same arguments. So pass x, y, A to all three and just ignore them where they are not needed.

第二,您必须在某处定义yA ...

Second, you have to define y and A somewhere...

第三,必须指定要使用的算法.使用opts=list(algoritm=...)执行此操作.事实证明,如果您(a)使用约束,并且(b)提供计算雅可比矩阵的函数,则仅其中一些算法是合适的.就您而言,opts=list(algorithm="NLOPT_GN_ISRES")似乎可行.

Third, you must specify which algorithm to use. Do this with 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. In your case opts=list(algorithm="NLOPT_GN_ISRES") seems to work.

最后,默认的maxeval = 100远远不够.我必须将其设置为100,000才能收敛.

Finally, the default maxeval = 100 which turns out to be not nearly enough. I had to set it to 100,000 to get convergence.

将所有这些放在一起,尽管具有一个虚构的目标函数:

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

这篇关于在非线性优化函数`nloptr`中传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆