scipy.optimize与非线性约束

时间:2017-04-09 17:42:47

标签: python numpy optimization scipy

我有非线性约束的非线性函数,我想优化它。我不知道如何使用scipy.optimize定义非线性约束。到目前为止我的代码看起来像:

from math import cos, atan
import numpy as np
from scipy.optimize import minimize
import sympy as sy

def f(x):
    return 0.1*x*y

def ineq_constraint(x):
    x**2 + y**2 - (5+2.2*sy.cos(10*sy.atan(x/y)))**2
    return x,y

con = {'type': 'ineq', 'fun': ineq_constraint}
minimize(f,x0,method='SLSQP',constraints=con)

1 个答案:

答案 0 :(得分:2)

代码中的一些小问题;这是修改后的版本(以下说明):

from math import cos, atan
import numpy as np
from scipy.optimize import minimize


def f(x):
    return 0.1 * x[0] * x[1]

def ineq_constraint(x):
    return x[0]**2 + x[1]**2 - (5. + 2.2 * cos(10 * atan(x[0] / x[1])))**2


con = {'type': 'ineq', 'fun': ineq_constraint}
x0 = [1, 1]
res = minimize(f, x0, method='SLSQP', constraints=con)

res如下所示:

     fun: 0.37229877398896682
     jac: array([ 0.16372866,  0.22738743,  0.        ])
 message: 'Optimization terminated successfully.'
    nfev: 96
     nit: 22
    njev: 22
  status: 0
 success: True
       x: array([ 2.27385837,  1.63729975])

一个问题是xy未在您的函数中定义,我分别用x[0]x[1]替换它们;此外,无需使用sympy来定义约束,并且您希望返回实际约束,而不是xy