[英]Optimization (with scipy.optimize.minimize) with multiple variables
I want to implement the Nelder-Mead optimization on an equation. 我想对一个方程实现Nelder-Mead优化。 But it does not contain only one variable, it contains multiple variables (one of them which is the unknown, and the others known.)
但是它不仅包含一个变量,还包含多个变量(其中一个是未知变量,另一个是已知变量。)
For instance at this example: http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html 例如,在此示例中: http : //docs.scipy.org/doc/scipy/reference/tutorial/optimize.html
If my rosen(x) was 如果我的rosen(x)是
def rosen(x,y):
... """The Rosenbrock function"""
... return sum(100.0*(x[1:]-x[:-1]**2.0)**y + (1-x[:-1])**2.0)
instead of this that is mentioned on the example, how could i optimise it? 而不是示例中提到的这个,我如何优化它? If i call
如果我打电话
res = minimize(rosen, x0, method='nelder-mead',
... options={'xtol': 1e-8, 'disp': True})
it says that needs two arguments if i call 它说如果我打电话需要两个参数
res = minimize(rosen(y), x0, method='nelder-mead',
... options={'xtol': 1e-8, 'disp': True})
with y already defined previously on the code, i get the same error. 与先前已经在代码上定义的y,我得到相同的错误。 While if I call it
如果我叫它
res = minimize(rosen(x,y), x0, method='nelder-mead',
... options={'xtol': 1e-8, 'disp': True})
I get an error that x is not defined. 我收到一个未定义x的错误。
Passing arguments to the objects is done with parameter args
. 将参数传递给对象是通过参数
args
完成的。 Optimizing rosen(x,2)
: 优化
rosen(x,2)
:
import numpy as np
from scipy.optimize import minimize
def rosen(x, y):
"""The Rosenbrock function"""
return sum(100.0*(x[1:]-x[:-1]**2.0)**y + (1-x[:-1])**2.0)
x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
res = minimize(rosen, x0, args=(2,), method='nelder-mead',
options={'xtol': 1e-8, 'disp': True})
Note that the variable x
is a 5 dimensional vector, as you can see in the definition of the starting point x0
, hence rosen(x,2)
has five variables. 请注意,变量
x
是一个5维向量,如您在起点x0
的定义中所见,因此rosen(x,2)
具有五个变量。 If your you want to minimize rosen(x,y)
, define a objective function 如果您要最小化
rosen(x,y)
,请定义一个目标函数
def rosen2(zz):
return rosen(zz[:5], zz[5])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.