passing a function with multiple independent variables and multiple arguments to scipy optimize minimize

戏子无情 提交于 2020-03-03 13:59:36

问题


Following this question, I want to make my question as specific as possible focusing on the part that I can not solve. Consider a very simple function of:

def foo(x, y, a, b, c):
    return a * x**4 + b * y**2 + c

now I want to use the scipy.optimize.minimize or any of other existing functions to find the x and y (i.e., parameters) to minimize foo given the constants a, b, and c (i.e., args). If I had only one parameter and multiples arguments then from this page I could do:

def foo(x, *args):
    a, b, c = args
    return a * x**4 + b * x**2 + c

# X0 = to some scalar
# ARGS = a tuple of scalars (A, B, C) 

x_min = scipy.optimize.minimize(foo, x0=X0, args=ARGS)

and if I had only independent variables, with no constant args, then from this page I could do:

def foo(*params):
    x, y = params
    return 4 * x**4 + 2 * y**2 + 1

# P0 = to a list of scalars [X0, Y0] 

x_min = scipy.optimize.minimize(foo, x0=P0)

However, I can not use any of the above syntaxes. I believe I have to define my function as something like:

def foo(*args, **kwargs):
    x, y = args
    a, b, c = tuple(kwargs.values())
    return a * x**4 + b * y**2 + c

but then I don't know how to pass args and kwargs to the scipy.optimize functions. I would appreciate if you could help me understand what is the best way to define the foo function with multiple independent parameters and constant arguments to scipy.optimize functions. Thanks for your support in advance.


回答1:


Instead of passing foo and making scipy pass the constant arguments, you can bind them yourself, either using lambda or functools.partial:

A, B, C = some_const_values
foo1 = lambda x, y: foo(x, y, A, B, C)

Or:

import functools
foo1 = functools.partial(foo, a=A, b=B, c=C)

Then:

x_min = scipy.optimize.minimize(foo1, ...)


来源:https://stackoverflow.com/questions/60396209/passing-a-function-with-multiple-independent-variables-and-multiple-arguments-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!