koch_kir
koch_kir

Reputation: 163

Scipy function muliple arguments

I have this function:

def error(w0, w1):
    return sum((data.Height - (w1*data.Weight+w0))**2)

and next I want to optimize it withres = scipy.optimize.minimize(error, (1, 2), ...

When I try to run it, I have error:TypeError: error() takes exactly 2 arguments (1 given)

I find what this error doesn't apper when I change my function to:

def error(w):
    return sum((data.Height - (w[1]*data.Weight+w[0]))**2)

But I want to understand why my first doesn't work.

Upvotes: 0

Views: 799

Answers (2)

hpaulj
hpaulj

Reputation: 231375

minimize(fun, x0, args=(), method=None,....):
"""
 minimize f(x) subject to
   ...
    where x is a vector of one or more variables.

So the first argument is your function, error, and the 2nd is x0, in your case a tuple, the initial guess. and the first the code does is turn x0 into an array, x0 = np.asarray(x0).

And look at an example function:

fun = lambda x: (x[0] - 1)**2 + (x[1] - 2.5)**2

I haven't used this much, but it sure looks like your function should work if you did:

error(np.array([1,2]))

That's consistent with your 2nd form, but not the first.

To put it another way, minimize works by starting with the initial value, np.array(x0), plugs that into error, and based on the return value tries other 2 element arrays, variations on that initial x0. It's not playing with multiple arguments, but with one argument with multiple elements.

Upvotes: 0

hashcode55
hashcode55

Reputation: 5860

Well if you look at the documentation of this function, it says that

scipy.optimize.minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)[source]

fun is your function here and args are the arguments that you are sending. Now in your first code your objective function has 2 parameters but what you are sending is a tuple and thats what should be done according to the documentation.

So in short what you are sending to the objective function is a tuple but there are 2 parameters over there, and thats why the error pops up.

And for the same reason your second code works as w is just a tuple here and thus the code works!

Upvotes: 1

Related Questions