使用矩阵的nloptr优化

x33g5p2x  于 2023-05-20  发布在  其他
关注(0)|答案(1)|浏览(150)

我想平衡一个不平衡的矩阵。不平衡的,指的是行和列的和与给定值不匹配。我做了一个小例子,矩阵U是起始矩阵,它的行和列和被用作不平衡矩阵Uu应该匹配的“新”值。我对行和列和有两个约束,还有一个目标函数。(实际上我有一个大小为60x60的矩阵,给定的行和列和是给定的,而不是从起始矩阵中取的)。我还定义了一些下限和上限。当我尝试运行下面的代码时,nloptr给出了以下错误:

Error in .checkfunargs(eval_f, arglist, "eval_f") : 
  u' passed to (...) in 'nloptr' but this is not required in the eval_f function.

下面是代码

library(nloptr)
U <- matrix(c(3,5,4,6),  ncol = 2, nrow = 2)
Uu <- matrix(c(3,5,4,5),  ncol = 2, nrow = 2)

eq_constr <- function(u, uu) {
  c(rowSums(uu) - rowSums(u),
  colSums(uu) - colSums(u))
}
  
obj_function <- function(u, uu) {
  sum(uu * log(uu/u))
}

opts <- list( "algorithm" = "NLOPT_GN_ISRES")

lb <- matrix(c(0,0,0,0), ncol = 2, nrow = 2)
ub <- matrix(c(1000, 1000, 1000, 1000), ncol = 2, nrow = 2)

res <- nloptr(
  x0 = u,
  lb          = lb,
  ub          = ub,
  eval_f      = obj_function,
  eval_g_eq   = eq_constr,
  opts        = opts,
  u           = U,
  uu          = Uu)
print(res)

像往常一样:任何帮助都将是感激的。
干杯
伦格尔

643ylb08

643ylb081#

这是可怕的:我从Bing的聊天机器人那里得到了一个答案,并用它来得到答案:

library(nloptr)
U <- matrix(c(3,5,4,6),  ncol = 2, nrow = 2)

eq_constr <- function(uu) {
  c(uu[1] + uu[2] - rowSums(U)[1],
    uu[3] + uu[4] - rowSums(U)[2],
    uu[1] + uu[3] - colSums(U)[1],
    uu[2] + uu[4] - colSums(U)[2]
    )
}

obj_function <- function(uu) {
  uu <- matrix(uu, nrow = 2)
  sum(uu * log(uu/U))
}

obj_function(uu)
uu <- x0
opts <- list( "algorithm" = "NLOPT_GN_ISRES")

lb <- matrix(c(0,0,0,0), ncol = 2, nrow = 2)
ub <- matrix(c(1000, 1000, 1000, 1000), ncol = 2, nrow = 2)

res <- nloptr(
  x0 = c(3,5,4,5),
  lb          = lb,
  ub          = ub,
  eval_f      = obj_function,
  eval_g_eq   = eq_constr,
  opts        = opts,

)
print(res)

不幸的是,现在的问题是我必须写出所有的约束(对于一个60x 60的矩阵)

相关问题