0

I have a function eqn which I want minimized by changing the values of two variables (floats), a and b. However, eqn uses a for loop to obtain values for constants, which are unrelated to a and b, from the lists list1 and list2, as shown:

def eqn(a, b, list1, list2):
    value = 0
    for i in range(len(list1):
        value = value + ((a - (1 - exp(- c * list1[i]) - list2[i]) ** 2)
    return value

I am unsure how to include the iterative inclustion of list members as constants in scipy.optimize.minimize, and I can't find any mention of it in the documentation

I have already got a nested for-loop to manually minimize the function by brute force w.r.t. a and b, but I cannot get to the precision level that I need before running into a mem error.

Any help would be greatly appreciated.

  • To be sure I have understood: are `list1` and `list2` two lists holding test values for `a` and `b`? – Valentino May 03 '19 at 18:25
  • Nope, they are lists that hold constants and are completely separate to `a` and `b` – P. H. Allus May 03 '19 at 19:47
  • have a look here: https://stackoverflow.com/questions/12200114/two-dimensional-optimization-minimization-in-python-using-scipy-optimize – Valentino May 03 '19 at 19:54
  • Thanks for pointing this out. I have yes, but I'm still confused as to how to implemenent constants into an equation to be minimized. – P. H. Allus May 03 '19 at 20:02

1 Answers1

0

According to minimize docs the function to be minimized must be in the form:

fun(x, *args) -> float
where x is an 1-D array with shape (n,) and args is a tuple of the fixed parameters needed to completely specify the function.

This means that your constants should be grouped in a single list (not two lists), and your variables too. For example:

def eqn(x, *param):
    value = 0
    ll = len(param)//2
    for i in range(ll):
        value = value + ((x[0] - (1 - math.exp(- x[1] * param[i]) - param[i+ll]) ** 2))
    return value

Here x is a list (so x[0] would be your a and x[1] your b) and param is your two lists concatenated: list1 + list2.

Note the asterisk: to use this function by itself (not as a minimize argument) you must do:

vars = (1, 2)
consts = (3, 4, 5, 6, 7, 8)
res = eqn(vars, *consts)

but defined this way, is eligible as an argument for minimize.

If you do not know the asterisk notation in function definition, you can find more info here or in the docs.

Valentino
  • 7,291
  • 6
  • 18
  • 34