仍在玩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'
我很困惑,我必须说。
答案 0 :(得分:1)
我不知道您想精确建模什么,但是这里有些有效:
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)
原因:更容易读出确切的情况。
您的问题:您的目标受到约束,这是不可能的。
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)
元素级Abs:好
最后的外部max
产生单个值,否则cp.Minimize
将不接受它。好
编辑或让我们让cvxpy变得更快乐:
obj = cp.Minimize(cp.norm(A*theta-b, "inf"))