如何使用scipy.optimize.minimize.最小化当你想计算梯度和目标函数的时候?

2024-10-04 09:29:03 发布

您现在位置:Python中文网/ 问答频道 /正文

scipy.optimize.minimze接受obj和{}函数作为输入。我会在需要的时候给他们打电话。但是我们经常遇到目标函数,它的梯度计算与目标函数的计算量相当大。所以理想情况下,我想同时计算obj和{}。但这个图书馆似乎不是这样的?如果一个人仍然想使用scipy.optimize.minimze如果有的话,该怎么处理呢?在


Tags: 函数obj目标图书馆情况scipyoptimize梯度
1条回答
网友
1楼 · 发布于 2024-10-04 09:29:03

你完全可以。只需使用jac=True

In [1]: import numpy as np

In [2]: from scipy.optimize import minimize

In [3]: def f_and_grad(x):
   ...:     return x**2, 2*x
   ...: 

In [4]: minimize(f_and_grad, [1], jac=True)
Out[4]: 
      fun: 1.8367099231598242e-40
 hess_inv: array([[ 0.5]])
      jac: array([  2.71050543e-20])
  message: 'Optimization terminated successfully.'
     nfev: 4
      nit: 2
     njev: 4
   status: 0
  success: True
        x: array([  1.35525272e-20])

实际上是documented

jac : bool or callable, optional Jacobian (gradient) of objective function. Only for CG, BFGS, Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg. If jac is a Boolean and is True, fun is assumed to return the gradient along with the objective function. If False, the gradient will be estimated numerically. jac can also be a callable returning the gradient of the objective. In this case, it must accept the same arguments as fun.

(重点是我的)

相关问题 更多 >