pythonscipy

Python Scipy: takes 1 positional argument but 2 were given


I'm trying to implement simple optimisation with Scipy lib:

   def f1(x):
          sum(x)

   initial_x_1 = np.ndarray([1])

   res = optimize.minimize(f1, initial_x_1, [], 'COBYLA')

But got the error:

    fx = fun(np.copy(x), *args)
     ^^^^^^^^^^^^^^^^^^^^^^

    TypeError: f1() takes 1 positional argument but 2 were given

Solution

  • The problem comes from the third and fourth arguments you passed to optimize.minimize; which are optional and should be named. Otherwise, they are assumed to be extra arguments which will be passed to f1():

    minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)
    

    args : tuple, optional. Extra arguments passed to the objective function and its derivatives (fun, jac and hess functions).


    The following modification should solve your problem:

    from scipy import optimize
    import numpy as np
    
    def f1(x):
           return sum(x)
    
    initial_x_1 = np.ndarray([1])
    
    res = optimize.minimize(f1, initial_x_1, method='COBYLA')