0

Is it possible to minimize a function fun(x,y) that depends on two arrays using the Scipy minimizer?

(x and y are two different 1D arrays with different length, e.g. x=np.array([1,2,3,1,52,5]) and y=np.array([4,8,9]))

I'm thinking for something like:

minimize(fun, [x,y], method="Powell", tol=1e-3)

Is this the correct way to go?

And thank you.

walid
  • 285
  • 1
  • 2
  • 8
  • What do you mean "depends on"? – Karl Knechtel Jul 31 '21 at 23:32
  • Which pairs do you want to pass to the function? – tobias Jul 31 '21 at 23:34
  • @KarlKnechtel I mean that takes as input x and y – walid Jul 31 '21 at 23:35
  • @tobias if I understood you well: I want both x and y – walid Jul 31 '21 at 23:37
  • Read what `minimize` expects. If necessary try something close to given examples, and make small steps away from that. – hpaulj Aug 01 '21 at 01:09
  • In other words, does your `fun` conform to `minimize` specs? `fun(x, *args)`, where `x` is an 1d array of size (n,), `args` is a tuple to just "goes along for the ride", and the value is a scalar? – hpaulj Aug 01 '21 at 01:34
  • @hpaulj Because my function takes values from both arrays respectively (for instance, in the above example the function evaluates first as: `fun(1,4)`, then `fun(2,8)`, then `fun(3,9)`...). So what I want from the minimizer is to optimize both arrays x and y at the same time. – walid Aug 01 '21 at 12:40

1 Answers1

1

Define a function that displays the argument that minimize supplies, along with its shape:

In [300]: def fun(x):
     ...:     print(x, x.shape)
     ...:     return np.sum(x)**2
     ...: 
     ...: 

Call minimize with a 2d array:

In [301]: minimize(fun, np.arange(6).reshape(2,3))
[0. 1. 2. 3. 4. 5.] (6,)
[1.49011612e-08 1.00000000e+00 2.00000000e+00 3.00000000e+00
 4.00000000e+00 5.00000000e+00] (6,)
[0.         1.00000001 2.         3.         4.         5.        ] (6,)
[0.         1.         2.00000001 3.         4.         5.        ] (6,)
[0.         1.         2.         3.00000001 4.         5.        ] (6,)
[0.         1.         2.         3.         4.00000001 5.        ] (6,)
[0.         1.         2.         3.         4.         5.00000001] (6,)
....

Note that the initial x0 (2,3), has been raveled to a (6,).

I think you take it from there.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • thank you for your answer. From your example of the function `fun(x)`, I guess the minimizer doesn't accept a function that takes as input two arrays. Because what matters for me is my function should take x & y as input. Is there another minimizer that allows this functionality? Otherwise, I will try to edit my function. – walid Aug 01 '21 at 21:36
  • 1
    You could use `x0=np.hstack((x,y))` and inside the function split `x` into the two parts. While `minimize` treats `x` as a 1d array of values, your function does not have to look at it that way. – hpaulj Aug 02 '21 at 00:30