使用R nloptr包最小化-多个相等约束 [英] Minimization with R nloptr package - multiple equality constraints

查看:99
本文介绍了使用R nloptr包最小化-多个相等约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在R的 nloptr 函数中指定多个相等约束?我尝试运行的代码如下:

Is it possible to specify more than one equality constraint in nloptr function in R? The code that I am trying to run is the following:

eval_f <- function( x ) {
  return( list( "objective" = x[3]^2+x[4]^2,
                "gradient" = c( 0,
                                0,
                                2*x[3],
                                2*x[4] ) ) )
}
# constraint functions
# equalities
eval_g_eq <- function( x ) {
  constr <- c( x[1] + x[2] + x[3] - 4,  
               x[1]^2 + x[2]^2 + x[4] - 15
  )
  grad <- c( c(1, 1, 1, 0),
             c(2*x[1], 2*x[2], 0, 1)
  )
  return( list( "constraints"=constr, "jacobian"=grad ) )
}
# initial values
x0 <- c( 1, 5, 5, 1 )
local_opts <- list( "algorithm" = "NLOPT_LD_MMA",
                    "xtol_rel" = 1.0e-7 )
opts <- list( "algorithm" = "NLOPT_LD_AUGLAG",
              "xtol_rel" = 1.0e-7,
              "maxeval" = 1000,
              "local_opts" = local_opts )
res <- nloptr( x0=x0,
               eval_f=eval_f,
               eval_g_eq=eval_g_eq,
               opts=opts)
print( res )

它产生的结果如下:

Current value of controls: -1.035323 3.093593 2.409501 0.2708714

但是这些值不具有相等约束,即

However these values do not hold equality constraints, i.e.

-1.035323 + 3.093593 + 2.409501 = 4.467771
(-1.035323)^2 + 3.093593^2 + 0.2708714 = 10.91308

我猜想要么无法在 nloptr 函数中指定多个相等约束,要么我以错误的方式传递了它们.我没有在软件包文档中找到任何具有多个平等约束的示例.

I guess that either it is impossible to specify multiple equality constraints in nloptr function or I passed them in the wrong way. I did not find any example having more than one equality constraint in package documentation.

更新

好,我解决了.这种情况是在 eval_g_eq 中指定 constr grad ,应该使用 rbind()而不是c().

Ok, I solved it. The case was that specifying constr and grad in eval_g_eq, one should use rbind() instead of c().

推荐答案

我最近在另一篇文章中回答了关于不等式约束的问题,但是您也应该能够使用 c()

I answered this in a different post recently for inequality constraints, but you should be able to return multiple equality constraints in a vector as well using c()

多个不平等约束"-使用R nloptr软件包最小化

这篇关于使用R nloptr包最小化-多个相等约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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