具有非线性约束的scipy.optimize [英] scipy.optimize with non linear constraints
问题描述
我具有带有非线性约束的非线性函数,我想对其进行优化.我不知道如何使用scipy.optimize定义非线性约束.到目前为止,我的代码如下:
I have non-linear function with non-linear constraints and I'd like to optimize it. I don't know how to define non-linear constraints using scipy.optimize. My code so far looks like:
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)
推荐答案
代码有一些小问题;这是修改后的版本(在下面说明):
The were a few minor issues with the code; here is the modified version (explanation below):
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])
一个问题是在您的函数中未定义x
和y
,我分别用x[0]
和x[1]
替换了它们;同样,也无需使用sympy
来定义约束,而您想返回实际约束,而不是x
和y
.
One problem was that x
and y
were not defined in your functions, I replaced them by x[0]
and x[1]
, respectively; also there was no need to use sympy
to define your constraints and you want to return the actual constraint and not x
and y
.
这篇关于具有非线性约束的scipy.optimize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!