gpt4 book ai didi

r - 最小化带有约束的 R 中的多元函数

转载 作者:行者123 更新时间:2023-12-02 14:31:15 25 4
gpt4 key购买 nike

我正在尝试最小化 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) 是初始值。

但是,我还有另外两个限制。我将第一个编写为函数:

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))

关于r - 最小化带有约束的 R 中的多元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49161536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com