在cvxpy中使用实际值检查约束是可以的 [英] Check constraints are ok in cvxpy with actual values
问题描述
在cvxpy中解决优化问题时,是否有一种好方法可以通过用优化变量的实际值代替约束来检查约束是否有效?
When solving optimisation problems in cvxpy, is there a nice way to check that the constraints are valid by substituing in actual values for the optimisation variables?
我有一个复杂的优化问题(超过100个约束),但是我知道最佳解决方案应该是什么.但是,cvxpy失败,并显示错误消息ValueError: Rank(A) < p or Rank([G; A]) < n
我认为这是因为我在其中一项约束中有错别字,使它们不一致.有没有一种很好的方法可以用实际值代替变量,以查看违反了哪些约束(因为它们可能有错别字)?
I have a complicated optimisation problem (100+ constraints), but I know what the optimal solution should be. However, cvxpy fails with error message ValueError: Rank(A) < p or Rank([G; A]) < n
I think this is because I have a typo in one of the constraints, making them inconsistent. Is there a nice way to substitute actual values for the variables, to see which constraints are violated (since they probably have typos)?
我的实际问题很复杂,因此我举了一个简单的例子:
My actual problem is complicated, so I've made a simple example:
from cvxpy import *
x = variable(name='x')
y = variable(name='y')
c1 = greater_equals(x, 1.)
c2 = greater_equals(y, 1.)
c3 = less_equals(x + y, -4.) # typo: -4 should be +4
p = program(maximize(2. * x + y), [c1, c2, c3])
p.solve()
约束c3
中的-4
应该为+4
.
这将失败,并显示错误消息:Certificate of primal infeasibility found.
如果输入p.show()
,我得到:
The -4
in constraint c3
should be +4
.
This fails with error message: Certificate of primal infeasibility found.
If I enter p.show()
I get:
maximize 2.0*x + y
subject to
x >= 1.0
y >= 1.0
x + y <= -4.0
是否有一个值可以替代正确的解决方案(x == 3., y == 1.
),以便查看是否违反了第三约束?我试过弄弄x.value
等,但是还没有找到方法
Is there a value to substitue the correct solution (x == 3., y == 1.
) so see that 3rd constraint is violated? I've tried messing around with x.value
etc. but haven't found a way
推荐答案
我找到了一种使用约束的left
属性的不错方法,该属性确实具有value
属性:
I've found an ok way to do it, using the left
attribute of the constraint, which does have a value
attribute:
x.value = 3.
y.value = 1.
for c in [c1, c2, c3]:
constraint_text = '%s %s %s' % (c.left.value, c.type, c.right)
print '%s becomes %s which is %s' % (c, constraint_text, eval(constraint_text))
打印:
x >= 1.0 becomes 3.0 >= 1.0 which is True
y >= 1.0 becomes 1.0 >= 1.0 which is True
x + y <= -4.0 becomes 4.0 <= -4.0 which is False
如果有人知道更好的方法,请随时分享.
If anyone knows a better way, feel free to share.
这篇关于在cvxpy中使用实际值检查约束是可以的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!