首页 > 解决方案 > R中的非线性有界优化

问题描述

我正在尝试在 R 中运行有界约束的非线性优化。我必须知道NlcOptimroptim可以用来优化非线性目标函数,并且我已经通过示例 [https://cran.r-project.org/web /packages/NlcOptim/NlcOptim.pdf] 就像我在下面提到的一个(ex1);

require(NlcOptim)
require(MASS)
objfun=function(x){
  return(exp(x[1]*x[2]*x[3]*x[4]*x[5]))
}
#constraint function
confun=function(x){
  f=NULL
  f=rbind(f,x[1]^2+x[2]^2+x[3]^2+x[4]^2+x[5]^2-10)
  f=rbind(f,x[2]*x[3]-5*x[4]*x[5])
  f=rbind(f,x[1]^3+x[2]^3+1)
  #return(list(ceq=f,c=NULL))
  return(list(ceq=f,c=NULL))
}
x0=c(-2,2,2,-1,-1)
solnl(x0,objfun=objfun,confun=confun)

理解: objfun 和 confun 中使用的 x 是一个包含 x(i) 的向量,i=1(1)5 x0 是起始值(在这种情况下,我有点困惑,因为我们没有在这里定义 x1 的边界,..,x5,而只是初始值)

我试图为我的实际问题复制这个例子,我构建的目标函数如下;

Maximize P= (x*y*z)-(cost1 + cost2 + cost3 + cost4 + cost5 + cost6) 
where
cost1 = 5000
cost2 = (0.23*cost1) + (0.67*x*y) 
cost3 = 0.2* cost1+ (0.138*x*y)
cost4 = 0.62*cost1
cost5 = 0.12* cost1
cost6 = 0.354*x
Boundaries for the variables are as follow;
200<=x=>350
17<=y=>60
964<=z=>3000

手头有这个问题,我试图将其表述为代码;

x <- runif(2037,200,350)
y <- runif(2037,17,60)
z <- seq(964,3000,1)  # z is having highest length of 2037. But not sure if this the way to define bounds!!
data_comb <- cbind(x,y,z)
mat <- as.matrix(data_comb)

cost1 <- 5000
cost2 <- (0.23*cost1) + (0.67* mat[,1])* (mat[,2]) 
cost3 <- 0.2* cost1+ (0.138* mat[,1])* (mat[,2])
cost4 <- rep(0.62*cost1, dim(mat)[1])
cost5 <- rep(0.12* cost1, dim(mat)[1])
cost6 <- 0.354* mat[,1]
#Objective function
objfun <- function(mat){
  return((mat[,1]*mat[,2]*mat[,3]) - (cost1 + cost2 + cost3 + cost4 + cost5 + cost6))
}
#Constraints
confun=function(mat){
  f=NULL
  f=rbind(f,(0.23*cos1) + (0.67*mat[,1])* (mat[,2]))
  f=rbind(f,(0.2*cost1) + (0.138*mat[,1])*(mat[,2]))
  f=rbind(f,0.354*mat[,1])
  return(list(ceq=f,c=NULL))
}
x0 <- c(200,17,964)
solnl(x0,objfun=objfun,confun=confun)

这给了我一个错误

Error in mat[, 2] : subscript out of bounds

我有一种感觉,我没有为我的问题正确地复制示例,但同时无法理解我所缺少的。我不知道我是否正确定义了边界或如何在函数中包含多元边界。请帮我解决这个优化问题。

TIA

标签: rconstraintsboundsnonlinear-optimization

解决方案


没有非线性约束,只有盒子约束,因此没有理由应用专门的包或功能。

obj <- function(v) {
    x <- v[1]; y <- v[2]; z <- v[3]
    cost1 <- 5000
    cost2 <- (0.23*cost1) + (0.67*x*y) 
    cost3 <- 0.2* cost1+ (0.138*x*y)
    cost4 <- 0.62*cost1
    cost5 <- 0.12* cost1
    cost6 <- 0.354*x
    w <- (x*y*z) - (cost1 + cost2 + cost3 + cost4 + cost5 + cost6)
    return(-w)
}

o <- optim(c(200,17,964), obj, method = "L-BFGS-B",
           lower = c(200,17,964), upper = c(350,60,3000))

o$par; -o$value
## [1]  350   60 3000
## [1] 62972058

对于使用,您可以使用和选项参数NlcOptim:solnl()定义框约束,就像上面一样。lbub

NlcOptim::solnl(c(200,17,964), obj,
                lb = c(200,17,964), ub = c(350,60,3000))

结果相同,表明您的函数没有真正的内部最大值。或者您可以将边界集成到约束函数中


推荐阅读