CVXPY 中的类型错误:float() 参数必须是字符串或数字,而不是 'Inequality'

TypeError in CVXPY: float() argument must be a string or a number, not 'Inequality'

还在玩 CVXPY。这次我得到一个有趣的错误。让我们看看这个最小的代码

import cvxpy as cp
import numpy as np

A = np.random.normal(0, 1, (64,6))
b = np.random.normal(0, 1, (64,1))
theta = cp.Variable(shape = (6,1))

prob = cp.Problem(
    cp.Minimize(cp.max(A*theta -b) <= 5),
    [-10 <= theta, theta <= 10])

编译后,出现以下错误:

~\Anaconda3\lib\site-packages\cvxpy\expressions\constants\constant.py in init(self, value) 42 self._sparse = True 43 else: ---> 44 self._value = intf.DEFAULT_INTF.const_to_matrix(value) 45 self._sparse = False 46 self._imag = None

~\Anaconda3\lib\site-packages\cvxpy\interface\numpy_interface\ndarray_interface.py in const_to_matrix(self, value, convert_scalars) 48 return result 49 else: ---> 50 return result.astype(numpy.float64) 51 52 # Return an identity matrix.

TypeError: float() argument must be a string or a number, not 'Inequality'

我不知道你到底想建模什么,但这里有一些有用的东西:

import cvxpy as cp
import numpy as np

A = np.random.normal(0, 1, (64,6))
b = np.random.normal(0, 1, (64,1))
theta = cp.Variable(shape = (6,1))

prob = cp.Problem(
            cp.Minimize(cp.sum(theta)),  # what do you want to minimize?
            [
                cp.max(A*theta -b) <= 5,
                -10 <= theta,
                theta <= 10
            ]
        )

有效并且应该显示问题。

我更喜欢更简洁的实现,例如:

import cvxpy as cp
import numpy as np

A = np.random.normal(0, 1, (64,6))
b = np.random.normal(0, 1, (64,1))
theta = cp.Variable(shape = (6,1))

obj = cp.Minimize(cp.sum(theta))          # what do you want to minimize?
                                          # feasibility-problem? -> use hardcoded constant: cp.Minimize(0)
constraints = [
    cp.max(A*theta -b) <= 5,
    -10 <= theta,
    theta <= 10
]

prob = cp.Problem(obj, constraints)

原因:更容易准确地读出正在发生的事情。

你的问题:你的objective有约束条件,这是不可能的。

import cvxpy as cp
import numpy as np

A = np.random.normal(0, 1, (64,6))
b = np.random.normal(0, 1, (64,1))
theta = cp.Variable(shape = (6,1))

prob = cp.Problem(
cp.Minimize(cp.max(A*theta -b) <= 5),  # first argument = objective
                                       # -> minimize (constraint) : impossible!
    [-10 <= theta, theta <= 10])       # second argument = constraints
                                       # -> box-constraints

简而言之:

  • 想要最小化函数
  • 最小化不平等

对下面的评论:

编辑

obj = cp.Minimize(cp.max(cp.abs(A*theta-b)))

小支票:

print((A*theta-b).shape)
(64, 1)
print((cp.abs(A*theta-b)).shape)
(64, 1)

Elementwise abs:好

最后的外层 max 结果是一个单一的值,否则 cp.Minimize 不会接受它。好

编辑 或者让 cvxpy 和我们更开心:

obj = cp.Minimize(cp.norm(A*theta-b, "inf"))