繁体   English   中英

使用约束最小化 R 中的多元函数

[英]minimize a multivariate function in R with constraints

我正在尝试最小化 R 中的函数S.residuum ,但有一些限制

S.residuum<- function(w, stdv, corr) {
  intermed<-0
  for (i in 1:length(stdvv)) {
  intermed =intermed+residuum(w,stdvv,corr.mat,i)
  }
  return(intermed)
}  

其中w是长度为 6 的向量。 约束如下所示:

0.03 <= w1 <= 0.27
0.03 <= w2 <= 0.27
0.20 <= w3 <= 0.91 
0.01 <= w4 <= 0.1
0.01 <= w5 <= 0.1
0.01 <= w6 <= 0.1

到目前为止,我能够实现它:

nlminb(c(1,1,1,1,1,1),S.residuum,hessian = NULL,
       lower=c(0.03,0.03,0.2,0.01,0.01), upper=c(0.27,0.27,0.91,0.1,0.1)),

其中c(1,1,1,1,1,1)是初始值。

但是,我还有 2 个其他限制。 我把第一个写成函数:

nequal <- function(w,stdv, corr) {
  intermed<-0
  for (j in 1:length(stdvv)) {
    for (i in 1:length(stdvv)) {
      intermed =intermed+ w[[i]] * w[[j]] * stdv[[i]] * stdv[[j]] * corr[[i]][[j]]
    }
  }
  intermed=sqrt(intermed)
},

其中stdv是向量, corr是矩阵。 应满足以下约束条件:

 1) nequal <=0.75
 2) w1+w2+w3+w4+w5+w6=1

有人可以对我说我怎么能在 R 中做到这一点? 谢谢!

您可以使用Rsolnp包中的函数solnp 代码如下所示:

library(Rsolnp)

# Inequality constraint
nequal <- function(w) {
 intermed <- 0
 for (j in 1:length(stdvv)) {
  for (i in 1:length(stdvv)) {
  intermed = intermed + w[[i]] * w[[j]] * stdvv[[i]] * stdvv[[j]] * corr.mat[[i]][[j]]
  }
 }
  sqrt(intermed)
}

# Equality constraint
equal <- function(w) {
  w[[1]]+w[[2]]+w[[3]]+w[[4]]+w[[5]]+w[[6]]
}

# Minimization with constraints
min <- solnp(c(0., 0., 0., 0., 0., 0.),
          S.residuum, 
          eqfun = equal,
          eqB = 1,
          ineqfun = nequal,
          ineqLB = 0,
          ineqUB = 0.075,
          LB = c(0.03, 0.03, 0.2, 0.01, 0.01, 0.01),
          UB = c(0.27, 0.27, 0.91, 0.1, 0.1, 0.1))

在这里找到了constrOptim() ,它对我来说效果很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM