【发布时间】:2022-08-02 18:03:12
【问题描述】:
我正在尝试使用 R 中的 ROI 包设置线性优化,遵循此链接中的说明:https://roi.r-forge.r-project.org/use_case_portfolio_optimization.html#introduction。但是,我在尝试实现“组约束”(https://roi.r-forge.r-project.org/use_case_portfolio_optimization.html#group_constraints)时遇到错误。这是我的示例代码
df <- data.frame(Group=rep(c(\'A\', \'B\', \'C\', \'D\'), each=4),
SubGroup=c(\'A.1\', \'A.2\', \'A.3\', \'A.1\', \'B.1\', \'B.1\', \'B.2\', \'B.2\', \'C.1\', \'C.2\', \'C.2\', \'C.2\', \'D.1\', \'D.2\', \'D.3\', \'D.4\'),
score=round(runif(16, 0, 1),2),
wgt=rep(1/16,16),
id=1:16)
data <- matrix(round(runif(256, -5, 5),3), ncol=16, byrow=TRUE)
Cov1 <- as.matrix(cov(data))
摘自链接文章:
group_constraint <- function(r_mat, index, coef.index = 1, dir = \"==\", rhs) {
## index = (i, j)
## coef.index = c(a,b)
## rhs = c
#x.names <- colnames(r_mat)
N <- NCOL(r_mat)
L <- rep(0, N)
L[index] <- coef.index
L_constraint(L = L, dir = dir, rhs = rhs)
}
group_1 <- group_constraint(df$score, index = c(3, 12, 13), dir = \"<=\", rhs = 0.5)
我的优化问题
full_invest <- L_constraint(rep(1, 16), \"==\", 1)
LP <- OP(objective = df$score,
group_1,
bounds = V_bound(ui = seq_len(16), ub = rep(0.40, 16)),
max = TRUE)
sol1 <- ROI_solve(LP, \"glpk\")
sol1
x <- solution(sol1)
x
当我运行它时,我收到以下错误:\“.check_constraints.L_constraint(constr, x) 中的错误:
尺寸不匹配! OP 有 16 个变量,约束有 13\"。如果我将 group_1 更改为 group_1 <- group_constraint(df$score, index = c(3, 12, 16), dir = \"<=\", rhs = 0.6) 这现在可以工作,因为 ncol(group_1) 是 16。
基于链接中的示例 1 (https://roi.r-forge.r-project.org/use_case_portfolio_optimization.html#example_1:_maximize_expected_return_subject_to_budget_normalization_and_group_constraints),我看不出我的示例哪里出错了。
任何帮助,将不胜感激。
标签: r optimization constraints roi