关于 CVXPY 求解器的奇怪输出的问题

计算科学 优化 Python 约束优化 凸优化 简历
2021-12-08 03:08:07

我正在熟悉 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))

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

Value of constraint at optimal x:3.0000000068183947

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

1个回答

您正在执行广播 ( A*x),而不是矩阵乘法 ( A@x),因此您的代码应如下所示:

#!/usr/bin/env python3

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: {0}'.format(np.linalg.norm(A@optimal_x - y)**2))

这使

Value of constraint at optimal x: 1.000000002699704