如何在`cvxpy`中对向量的一部分求和?
How to sum part of a vector in `cvxpy`?
我正在使用 cvxpy
来解决凸优化问题,这是我的约束条件:
那么如何在 cvxpy
中表达这个约束呢? cvxpy
中的sum_entries
函数只能对整个matrix/vector求和,不能对向量的一部分求和
只是 select 使用索引的一个子集(在以下示例中:基于经典 python 的切片;但更复杂的索引/numpy 样式是可能的):
示例:
from cvxpy import *
x = Variable(5)
constraints = []
constraints.append(x >= 0) # all vars
constraints.append(x <= 10) # all vars
constraints.append(sum_entries(x[:3]) <= 3) # only part of vector; sum(first-three) <=3
objective = Maximize(sum_entries(x))
problem = Problem(objective, constraints)
problem.solve()
print(problem.status)
print(x.value.T)
输出:
optimal
[[ 1. 1. 1. 10. 10.]]
我也怀疑你误解了这里的问题,但是公式图像当然是不完整的,无法实现。
我正在使用 cvxpy
来解决凸优化问题,这是我的约束条件:
那么如何在 cvxpy
中表达这个约束呢? cvxpy
中的sum_entries
函数只能对整个matrix/vector求和,不能对向量的一部分求和
只是 select 使用索引的一个子集(在以下示例中:基于经典 python 的切片;但更复杂的索引/numpy 样式是可能的):
示例:
from cvxpy import *
x = Variable(5)
constraints = []
constraints.append(x >= 0) # all vars
constraints.append(x <= 10) # all vars
constraints.append(sum_entries(x[:3]) <= 3) # only part of vector; sum(first-three) <=3
objective = Maximize(sum_entries(x))
problem = Problem(objective, constraints)
problem.solve()
print(problem.status)
print(x.value.T)
输出:
optimal
[[ 1. 1. 1. 10. 10.]]
我也怀疑你误解了这里的问题,但是公式图像当然是不完整的,无法实现。