为什么我得到一个错误,当我运行BFGS优化在scipy?



我还在学习scipy中的优化函数,所以作为一个测试,我想优化

def f(x):
return (x-2)**2+2

这应该给出最小值(2,2),然后我设置x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])。当我运行res = minimize(f, x0, method='BFGS', options={'disp': True})时,我得到了以下错误

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/scipy/optimize/optimize.py in _minimize_bfgs(fun, x0, args, jac, callback, gtol, norm, eps, maxiter, disp, return_all, finite_diff_rel_step, **unknown_options)
1211         try:
-> 1212             old_fval = old_fval.item()
1213         except (ValueError, AttributeError) as e:
ValueError: can only convert an array of size 1 to a Python scalar
The above exception was the direct cause of the following exception:
ValueError                                Traceback (most recent call last)
<ipython-input-16-a687d5eaf37f> in <module>
----> 1 res = minimize(f, x0, method='BFGS', options={'disp': True})
/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
616         return _minimize_cg(fun, x0, args, jac, callback, **options)
617     elif meth == 'bfgs':
--> 618         return _minimize_bfgs(fun, x0, args, jac, callback, **options)
619     elif meth == 'newton-cg':
620         return _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,
/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/scipy/optimize/optimize.py in _minimize_bfgs(fun, x0, args, jac, callback, gtol, norm, eps, maxiter, disp, return_all, finite_diff_rel_step, **unknown_options)
1212             old_fval = old_fval.item()
1213         except (ValueError, AttributeError) as e:
-> 1214             raise ValueError("The user-provided "
1215                              "objective function must "
1216                              "return a scalar value.") from e
ValueError: The user-provided objective function must return a scalar value.

有人能告诉我发生了什么吗?

您正在复制scipy.optimize.minimize示例中用于scipy.optimize.rosenx0: Rosenbrock目标函数。Rosenbrock函数对您提供的各种x0值应用sum(),因此求值为标量。

注意BFGS本质上是要使用函数及其在点(x)的导数。x0只是起点(一个试解),算法从这里开始寻找解。如果你的目标函数只提供一个标量,你不能传递多个x0值给它。

# This should work for you
from scipy.optimize import minimize
x0 = 1.3 # an initial value for f(x)
res = minimize(f, x0, method='BFGS', options={'disp': True})

什么时候可以/应该传递多个x0值?

假设你的目标函数有如下形式。这将要求您为x0提供一个包含5个初始值的数组。

def f(x):
return 10.0 * (x[0]**3 - 0.5 * x[1]**2 + 7.0 * x[2]**(-1.5)) - 6.0 * (x[3] - 2*x[4])**2
引用

  • scipy.optimize.rosen: Rosenbrock

  • scipy.optimize.minimize

最新更新