最小化 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)
是初始值。
但是,我还有另外两个限制条件。我把第一个写成一个函数:
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()
here,对我来说效果很好。
我正在尝试最小化 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))
我发现 constrOptim()
here,对我来说效果很好。