Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scipy.minimize - "TypeError: numpy.float64' object is not callable running"

Running the scipy.minimize function "I get TypeError: 'numpy.float64' object is not callable". Specifically during the execution of:

    .../scipy/optimize/optimize.py", line 292, in function_wrapper
return function(*(wrapper_args + args))

I already looked at previous similar topics here and usually this problem occurs due to the fact that as first input parameter of .minimize is not a function. I have difficulties in figure it out, because "a" is function. What do you think?

    ### "data" is a pandas data frame of float values
    ### "w" is a numpy float array i.e. [0.11365704 0.00886848 0.65302202 0.05680696 0.1676455 ]

    def a(data, w):
        ### Return a negative float value from position [2] of an numpy array of float values calculated via the "b" function i.e -0.3632965490830499 
        return -b(data, w)[2]

    constraint = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})

    ### i.e ((0, 1), (0, 1), (0, 1), (0, 1), (0, 1))
    bound = tuple((0, 1) for x in range (len(symbols)))

    opts = scipy.minimize(a(data, w), len(symbols) * [1. / len(symbols),], method = 'SLSQP', bounds = bound, constraints = constraint)
like image 513
Nipper Avatar asked Apr 11 '18 13:04

Nipper


2 Answers

Short answer

It should instead be:

opts = scipy.minimize(a, len(symbols) * [1. / len(symbols),], args=(w,), method='SLSQP', bounds=bound, constraints=constraint)

Details

a(data, w) is not a function, it's a function call. In other words a(data, w) effectively has the value and type of the return value of the function a. minimize needs the actual function without the call (ie without the parentheses (...) and everything in-between), as its first parameter.

From the scipy.optimize.minimize docs:

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

...

fun : callable

The objective function to be minimized. Must be in the form f(x, *args). The optimizing argument, x, is a 1-D array of points, and args is a tuple of any additional fixed parameters needed to completely specify the function.

...

args : tuple, optional

Extra arguments passed to the objective function...

So, assuming w is fixed (at least with respect to your desired minimization), you would pass it to minimize via the args parameter, as I've done above.

like image 186
tel Avatar answered Nov 14 '22 23:11

tel


You're not passing the function, but the evaluated result to minimize.

opts = scipy.minimize(a,  len(symbols) * [1. / len(symbols),], method = 'SLSQP', bounds = bound, constraints = constraint, args = (data,w))

Should work.

Edit: Fixed stupid syntax error.

like image 24
mgutsche Avatar answered Nov 14 '22 21:11

mgutsche