使用实际值检查 cvxpy 中的约束是否正常

mje*_*sen 4 python optimization convex-optimization cvxpy

在 cvxpy 中解决优化问题时,是否有一种很好的方法可以通过替换优化变量的实际值来检查约束是否有效?

我有一个复杂的优化问题(100 多个约束),但我知道最佳解决方案应该是什么。但是, cvxpy 失败并显示错误消息ValueError: Rank(A) < p or Rank([G; A]) < n 我认为这是因为我在其中一个约束中有一个错字,使它们不一致。有没有一种很好的方法来替换变量的实际值,以查看违反了哪些约束(因为它们可能有拼写错误)?

我的实际问题很复杂,所以我做了一个简单的例子:

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()
Run Code Online (Sandbox Code Playgroud)

-4在约束c3应该是+4。这失败并显示错误消息:Certificate of primal infeasibility found. 如果我输入,p.show()我得到:

maximize 2.0*x + y
subject to
x >= 1.0
y >= 1.0
x + y <= -4.0
Run Code Online (Sandbox Code Playgroud)

是否有替代正确解 ( x == 3., y == 1.)的值,以便看到违反了第三个约束?我试过搞乱x.value等,但还没有找到方法

mje*_*sen 5

我找到了一个不错的方法,使用left约束的属性,它确实有一个value属性:

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))
Run Code Online (Sandbox Code Playgroud)

打印:

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
Run Code Online (Sandbox Code Playgroud)

如果有人知道更好的方法,请随时分享。