【问题标题】:Contradicting output from the CVXPY solverCVXPY 求解器的输出相互矛盾
【发布时间】:2018-12-26 15:54:33
【问题描述】:

我正在熟悉 CVXPY,遇到了一个奇怪的问题。我有以下简单的玩具优化问题:

import numpy as np
import cvxpy as cp

A=np.array([[1,0,0],[0,1,0], [0,0,1]])
y=np.array([1,1,1])

# Upper bound for the constraint term
upper=1
# Solve the optimization problem using CVXPY
x = cp.Variable(3)
objective = cp.Minimize(cp.sum_squares(x))
constraint = [cp.sum_squares(A*x - y) <= upper]
prob = cp.Problem(objective, constraint)
prob.solve()
optimal_x = x.value

print('Value of constraint at optimal x:' + str(np.linalg.norm(A*optimal_x - y)**2))

现在,我希望我的输出编号比upper=1 更小,但我得到的是以下内容:

Value of constraint at optimal x:3.0000000068183947

我很困惑这怎么可能是真的。我是否错误地使用了函数cp.sum_squares?我只是以错误的方式设置优化吗?任何帮助表示赞赏!

【问题讨论】:

    标签: python optimization mathematical-optimization numerical-methods cvxpy


    【解决方案1】:

    我认为混淆源于numpy 中的错误矩阵乘法:

    >>> A * optimal_x - y
    array([[-0.57735027, -1.        , -1.        ],
           [-1.        , -0.57735027, -1.        ],
           [-1.        , -1.        , -0.57735027]])
    

    其实我认为你想要的是

    >>> np.dot(A, optimal_x) - y
    array([-0.57735027, -0.57735027, -0.57735027])
    

    这确实不违反约束(在舍入误差内):

    >>> np.linalg.norm(np.matmul(A, optimal_x) - y) ** 2
    1.000000002699704
    

    另请参阅thisnumpy 中有关矩阵数组乘法的问题。

    这确实令人困惑,因为 CVXPY 对象确实可以正确处理 * 运算符,即使是 numpy 类型:

    >>> (A * x - y).value
    array([-0.57735027, -0.57735027, -0.57735027])
    

    另请注意,对于您在CVXPY 中构造的任何表达式树,在优化之后,您可以在给定优化后的x 值的情况下查询该表达式的值:

    >>> cp.sum_squares(A*x - y).value
    array(1.)
    

    【讨论】:

      猜你喜欢
      • 2022-12-04
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多