Home > Software engineering >  Calling function into another function scipy.minimize. missing 3 required positional arguments:
Calling function into another function scipy.minimize. missing 3 required positional arguments:

Time:11-19

I want to understand how to call another function into function. For example, I want to approximate data by rational function, so I want to minimize approximation function. I use

def rational(a, b, c, d, x):
    return (a * x   b) / (x ** 2   c * x   d)

def approximate(a, b, c, d, x, y, func):
    return np.sum( (func(a, b, c, d, x) - y) ** 2 )

I want to pass rational into approximate and after that pass it to scipy.minimize like

minimize(approximate, x0=(0, 0, 0, 0), args=(X, Y, rational,), method='Nelder-Mead')

But the error is appear: approximate() missing 3 required positional arguments: 'x', 'y', and 'func'

So I want to understand how I should work with such constructions and best practices with working to

CodePudding user response:

You are passing a function with 7 arguments to minimize, but it expects a function with signature fun(x, *args). If you really want to pass the additional function arguments by minimize's args parameter, you can do something like this:

minimize(lambda z, *args: approximate(*z, *args), x0=(0, 0, 0, 0), args=(X, Y, rational), method='Nelder-Mead')

Here, *z unpacks all arguments. However, a much cleaner solution would be:

minimize(lambda z: approximate(*z, X, Y, rational), x0=(0, 0, 0, 0), method='Nelder-Mead')

CodePudding user response:

I solved the problem using a, b, c, d = params into functions. Working code is

def rational(params, x):
    a, b, c, d = params
    return (a * x   b) / (x ** 2   c * x   d)

def approximate(params, x, y, func):
    return np.sum( (func(params, x) - y) ** 2 )

nm_coefs = minimize(approximate, x0=(0, 1, 3, 2), args=(X, Y, rational,), method='Nelder-Mead')
  • Related