Attempt 1Using CVXR, I tried declaring split_index and using that as an index (e.g., x[1:split]):library(CVXR)split_index = Variable(1, integer = TRUE)objective = Minimize(abs(sum(x[1:split_index]) - sum(x[(split_index+1):length(x)])))result = solve(objective)使用 NA/NaN参数错误的 1:split_index .声明一个明确的索引向量( indices )并进行元素逻辑测试,以确定 split_index< =索引.然后将那个二进制向量与 x 逐元素相乘以选择拆分的一侧或另一侧:Declare an explicit index-vector (indices) and do an elementwise logical test whether split_index <= indices. Then element-wise-multiply that binary vector with x to select one or the other side of the split:indices = seq_along(x)split_index = Variable(1, integer = TRUE)is_first = split_index <= indicesobjective = Minimize(abs(sum(x * is_first) - sum(x * !is_first)))result = solve(objective)在 x * is_first 中出现错误,并为二进制运算符提供了非数字参数.我怀疑出现此错误是因为 is_first 现在是一个 IneqConstraint 对象.It errs in x * is_first with non-numeric argument to binary operator. I suspect that this error arises because is_first is now an IneqConstraint object.推荐答案红色的符号是决策变量,蓝色的符号是常量.Symbols in red are decision variables and symbols in blue are constants. R代码:> library(Rglpk)> library(CVXR)>> x <- c(1, 3, 6, 4, 7, 9, 6, 2, 3)> n <- length(x)> delta <- Variable(n, boolean=T)> y <- Variable(2)> order <- list()> for (i in 2:n) {+ order[[as.character(i)]] <- delta[i-1] <= delta[i]+ }>>> problem <- Problem(Minimize(abs(y[1]-y[2])),+ c(order,+ y[1] == t(1-delta) %*% x,+ y[2] == t(delta) %*%x))> result <- solve(problem,solver = "GLPK", verbose=T)GLPK Simplex Optimizer, v4.4730 rows, 12 columns, 60 non-zeros 0: obj = 0.000000000e+000 infeas = 4.100e+001 (2)* 7: obj = 0.000000000e+000 infeas = 0.000e+000 (0)* 8: obj = 0.000000000e+000 infeas = 0.000e+000 (0)OPTIMAL SOLUTION FOUNDGLPK Integer Optimizer, v4.4730 rows, 12 columns, 60 non-zeros9 integer variables, none of which are binaryInteger optimization begins...+ 8: mip = not found yet >= -inf (1; 0)+ 9: >>>>> 1.000000000e+000 >= 0.000000000e+000 100.0% (2; 0)+ 9: mip = 1.000000000e+000 >= tree is empty 0.0% (0; 3)INTEGER OPTIMAL SOLUTION FOUND> result$getValue(delta) [,1] [1,] 0 [2,] 0 [3,] 0 [4,] 0 [5,] 0 [6,] 1 [7,] 1 [8,] 1 [9,] 1> result$getValue(y) [,1][1,] 21[2,] 20>绝对值由CVXR自动线性化.The absolute value is automatically linearized by CVXR. 这篇关于在线性编程中使用索引进行优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-11 18:13