[SOLVED] Error while passing two arguments to scipy.optimize.minimize

Issue

This Content is from Stack Overflow. Question asked by Roberto Slepetys

I am trying to find a local minimum of a 2 variables function, but I am struggling with the syntax of scipy.optimize.minimize, as it looks like it is not accepting how I am passing the initial point:

import scipy.optimize as sop
function = lambda x,y: 2*(x**2)*(y**2)+3*x*x+2*x+4*y+7
p0 = [0,0]
min_ = sop.minimize (function,x0=p0)

Resulting in the following error:

TypeError: <lambda>() missing 1 required positional argument: 'y'

passing the values directly to the function, such as:

function(0,0)

works without issue.

But, if I pass an array or a tuple, it results in the same error:

x0 = (0,0)
function(x0)

TypeError: <lambda>() missing 1 required positional argument: 'y'

Help appreciated!

Thank you



Solution

Your function is a function of two scalar variables, but scipy.optimize.minimize expects a function of one (typically non-scalar) variable. So you only need to rewrite your objective function:

def function(xy):
    # unpack the vector xy into its components x and y
    x, y = xy
    return 2*(x**2)*(y**2)+3*x*x+2*x+4*y+7

p0 = [0, 0]
min_ = sop.minimize(function,x0=p0)


This Question was asked in StackOverflow by Roberto and Answered by joni It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?