【发布时间】:2020-07-25 08:55:09
【问题描述】:
我正在尝试在 R 中运行有界约束的非线性优化。
我必须知道NlcOptim & roptim 可以用来优化非线性目标函数,我已经通过示例 [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)
理解: x 用于 objfun 和 confun,是一个包含 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
【问题讨论】:
-
在示例中,函数在其中使用向量。而
x0也是一个向量。但是在您的设置中,您在函数中使用了名为 mat 的矩阵,但您仍然为函数提供了一个向量,即x0。所以它将它作为x0[,2]并且找不到维度,因为它是一个向量!这就是您收到 subscript out of bounds 警告的原因。我认为你应该打电话给solnl(mat,objfun=objfun,confun=confun)。或者其他一些至少有三列的矩阵。 -
如果我用 mat 替换 x0 会得到同样的错误。如果我需要使用mat,x0的作用是什么? @maydin
-
我的意思是,在示例代码中,没有定义向量 x。但它完美地工作。所以这意味着,它需要 x0(初始值)并将其传递到函数中。您正在复制它,但在您仍在使用向量时使用了矩阵。问题是,如果初始值在向量中,如何在矩阵中传递它们?
-
你能用一些代码解释并解决问题吗?
-
我对我定义边界的方式也没有信心......所以如果可以请发布一些代码来解决它会有所帮助
标签: r constraints bounds nonlinear-optimization