Scipy.optimize成功终止不可行的NLP

时间:2017-03-02 23:52:52

标签: python optimization scipy nonlinear-optimization

尝试使用scipy.optimize SLSQP解决NLP问题。问题显然是不可行的,但scipy.optimize中的最小化功能似乎不同意。

minimize X^2 + Y^2 
subject to 
X + Y = 11
X, Y >= 6

代码:

from scipy.optimize import minimize

def obj(varx):
    return varx[1]**2 + varx[0]**2

def constr1(varx):
    constr1 = -varx[0]-varx[1]+11
    return constr1


bnds = [(6,float('Inf')),(6,float('Inf'))]
ops = ({'maxiter':100000, 'disp':'bool'})
cons = ({'type':'eq', 'fun':constr1})       
res = minimize(obj, x0=[7,7], method='SLSQP', constraints = cons, bounds = bnds, options = ops)

print res.x
print res.success

输出:

Optimization terminated successfully.    (Exit mode 0)
            Current function value: 72.0
            Iterations: 6
            Function evaluations: 8
            Gradient evaluations: 2
[ 6.  6.]
True

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试mystic。它无法解决无法解决约束问题的问题。尽管不是“显而易见的”(也许),但它为不可行的解决方案返回了inf……我想可以改善行为(我是作者),以便更明显地发现只有不可行的解决方案。

>>> def objective(x):
...   return x[0]**2 + x[1]**2
... 
>>> equations = """
... x0 + x1 = 11
... """
>>> bounds = [(6,None),(6,None)]
>>> 
>>> from mystic.solvers import fmin_powell, diffev2
>>> from mystic.symbolic import generate_constraint, generate_solvers, simplify
>>>
>>> cf = generate_constraint(generate_solvers(simplify(equations)))
>>>
>>> result = fmin_powell(objective, x0=[10,10], bounds=bounds, constraints=cf, gtol=50, disp=True, full_output=True)
Warning: Maximum number of iterations has been exceeded
>>> result[1]
array(inf)
>>>
>>> result = diffev2(objective, x0=bounds, bounds=bounds, constraints=cf, npop=40, gtol=50, disp=True, full_output=True)
Warning: Maximum number of iterations has been exceeded
>>> result[1]
inf