Reputation: 13
I want to know if it is possible to use one function that returns both the objective value and jacobian, such that the program does not have to calculate some values twice.
I want to use it in Python's scipy optimize minimize routine. In the examples https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html they do not do this, so I am just wondering if it is possible.
What I am looking for is something like:
def obj_jac(c1):
A2 = RR*A1 + y1 - c1
obj = some_fun1(A2)
jac = some_fun2(A2)
return obj,jac
and then:
sol = minimize(obj_jac[0],c1_0,jac=obj_jac[1])
The objective is the first returned value of obj_jac and the jacobian is the second. However, the above format gives the error: "TypeError: 'function' object is not subscriptable".
Here is the current code that works, but calculates A2 twice:
def obj_fun(c1):
A2 = RR*A1 + y1 - c1
obj = some_fun1(A2)
return obj
def jac_fun(c1):
A2 = RR*A1 + y1 - c1
jac = some_fun2(A2)
return jac
sol = minimize(obj_fun,c1_0,jac=jac_fun)
Is there a way to avoid having to calculate A2 twice? (this is just a very simple example).
Upvotes: 1
Views: 1167
Reputation: 16174
the docs for minimize say:
jac{callable, ‘2-point’, ‘3-point’, ‘cs’, bool}, optional
If jac is a Boolean and is True, fun is assumed to return the gradient along with the objective function.
so just use:
sol = minimize(obj_jac, c1_0, jac=True)
see https://stackoverflow.com/a/37735355/1358308
Upvotes: 3