hendriksc1
hendriksc1

Reputation: 59

Scipy minimize objective element-wise

I am trying to apply a scipy minimizer to a vectorized objective function that takes multiple np.arrays as arguments. In this example I want to element-wise minimize obj(x,p) with respect to x while taking p as fixed. With p = np.array([2,3,4]) the minima should be 2, 3 and 4.

But

import numpy as np
from numba import vectorize, float64
from scipy.optimize import minimize
xinit = np.array([1,1,1])
p = np.array([2,3,4])

@vectorize([float64(float64,float64)])
def obj(x,p):
    return((x-p)**2)

minimize(obj, x0 = xinit,args = p, method='Nelder-Mead')

returns a ValueError: setting an array element with a sequence.

Who can help?

Thanks a lot in advance!

Upvotes: 1

Views: 394

Answers (1)

fuglede
fuglede

Reputation: 18201

It is not immediately clear what you are trying to achieve: (x-p)**2 is an array, so using that as an objective is not a well-defined operation (as there is no reasonable ordering to use). Perhaps you actually want the squared distance between the two parameters? I.e. what amounts to

def obj(x, p):
    return np.linalg.norm(x-p)**2

This will work and find the proper minimum, but at this point the vectorize signature is no longer valid; the callable can still be JIT compiled with Numba if you desire though.

Upvotes: 1

Related Questions