[英]scipy.optimize with matrix constraint
How do I tell fmin_cobyla
about a matrix constraint Ax-b >= 0
? 我如何告诉fmin_cobyla
有关矩阵约束Ax-b >= 0
? It won't take it as a vector constraint: 不会将其视为向量约束:
cons = lambda x: dot(A,x)-b
thanks. 谢谢。
Since the constraint must return a scalar value, you could dynamically define the scalar constraints like this: 由于约束必须返回标量值,因此可以动态定义标量约束,如下所示:
constraints = []
for i in range(len(A)):
def f(x, i = i):
return np.dot(A[i],x)-b[i]
constraints.append(f)
For example, if we lightly modify the example from the docs , 例如,如果我们从docs轻松修改示例 ,
def objective(x):
return x[0]*x[1]
A = np.array([(1,2),(3,4)])
b = np.array([1,1])
constraints = []
for i in range(len(A)):
def f(x, i = i):
return np.dot(A[i],x)-b[i]
constraints.append(f)
def constr1(x):
return 1 - (x[0]**2 + x[1]**2)
def constr2(x):
return x[1]
x = optimize.fmin_cobyla(objective, [0.0, 0.1], constraints+[constr1, constr2],
rhoend = 1e-7)
print(x)
yields 产量
[-0.6 0.8]
PS. PS。 Thanks to @seberg for pointing out an earlier mistake. 感谢@seberg指出了先前的错误。
Actually the documentation says Constraint functions;
实际上,文档说Constraint functions;
, it simply expects a list of functions each returning only a single value. ,它只是期望一个函数列表,每个函数仅返回一个值。
So if you want to do it all in one, maybe just modify the plain python code of the fmin_cobyla
, you will find there that it defines a wrapping function around your functions, so it is easy... And the python code is really very short anyways, just small wrapper around scipy.optimize._cobyal.minimize
. 因此,如果您想fmin_cobyla
,或者只需修改fmin_cobyla
的纯Python代码,您就会发现它在函数周围定义了一个包装函数,因此很容易...而且python代码确实非常无论如何,还是简短的,只是围绕scipy.optimize._cobyal.minimize
小包装。
On a side note, if the function you are optimizing is linear (or quadratic) like your constraints, there are probably much better solvers out there. 附带一提,如果您要优化的函数像约束一样是线性的(或二次函数),那么可能会有更好的求解器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.