0

I have a function

def f(x,a):
    x1, x2 = x
    val = np.sum(a)
    return val*x1**2+x2

where x are the parameters I want to optimize, and a is input data which is in the form of a 2D array. I believe fmin is the correct solver to do this. When I try the line

xopt = sp.optimize.fmin(f, x0, xtol=1e-8, args=(np.zeros((5,5))))

I get the error

operands could not be broadcast together with shapes (1,2) (5,5) 

which sounds like it's trying to concatenate the two variables with the input data shape, hence why it doesn't work. I've done this type of thing with matlab many times using fminsearch, but can't seem to get it to work with python. Does anyone have any idea?

user2551700
  • 89
  • 1
  • 6

1 Answers1

0

As @hpaulj noted in the comments, you forgot a comma passing an invalid args parameter that raises the error you see. Anyway the 'correct' code:

xopt = optimize.fmin(f, guess, args=(np.zeros((5,5,)),))

will probably do not do what you think, since val will always be 0.

The function sp.optimize.fmin finds the minimum of a function. The parameter x0 it is the initial guess. For example, for a 2D parabola:

def par2d(X0):
   x, y = X0
   return (x**2 + y**2)

we can find the x and y values of the minimum:

from scipy import optimize
guess = (1, 1)
min_pars = optimize.fmin(par2d, guess)
print(min_pars)

yields:

Optimization terminated successfully.
         Current function value: 0.000000
         Iterations: 38
         Function evaluations: 69
[-2.10235293e-05  2.54845649e-05]

which is close enough to [0, 0].

The parameter args should be an iterable (1D) with extra parameters that will be passed to the function to minimize and will not be optimized. For example, for a generalized parabola:

def par2d(X0, eccentricity=(1, 1)):
   x, y = X0
   ex_x, ex_y = eccentricity
   return (x**2 * ex_x + y**2 * ex_y)

we can pass the eccentricity as a non-adjustable parameter

min_pars = optimize.fmin(par2d, guess, args=((1,100), ))

In your case (after adding the missing comma) the sum of a zero-filled array will always be 0, val will always be 0 and the value of x1 will be rendered irrelevant. I do not know what 'optimize' the parameters means in this context, but I am confident that what you are doing will not yield what you want.

azelcer
  • 1,383
  • 1
  • 3
  • 7