结合 objective 和 jacobian 用于 Python 的 scipy 最小化

Combine objective and jacobian for Python's scipy minimize

我想知道是否可以使用一个 returns 函数同时包含 objective 值和 jacobian,这样程序就不必计算某些值两次。

我想在 Python 的 scipy 优化最小化例程中使用它。在示例中 https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html 他们没有这样做,所以我只是想知道这是否可能。

我要找的是这样的:

 def obj_jac(c1):
    A2 = RR*A1 + y1 - c1

    obj = some_fun1(A2)
    jac = some_fun2(A2)
    return obj,jac

然后:

  sol = minimize(obj_jac[0],c1_0,jac=obj_jac[1])

objective是obj_jac的第一个返回值,jacobian是第二个。但是,上面的格式给出了错误:"TypeError: 'function' object is not subscriptable".

这是当前有效的代码,但计算了 A2 两次:

 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)

有没有办法避免计算 A2 两次? (这只是一个很简单的例子)

minimize 的文档说:

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.

所以只需使用:

sol = minimize(obj_jac, c1_0, jac=True)