0

所以我正在尝试编写一个 scipy.optimize.minimize 的最小工作示例,而不仅仅是一个示例。

基本上,我的示例适用于一个变量的 lambda 函数,但只要我添加另一个变量,它就会崩溃。

lamX = lambda x: (x-2)**2
q0X = np.ones(1)
solX = optimize.minimize(lamX, x0=q0X)

lamXY = lambda x,y: (x-2)**2 + y**2
q0XY = np.ones(2)
solXY = optimize.minimize(lamXY, x0=q0XY)

前三行执行没有错误并给出正确的结果,但最后三行给我以下错误

    solXY = optimize.minimize(lamXY, x0=q0XY)
  File "/usr/lib/python3/dist-packages/scipy/optimize/_minimize.py", line 444, in minimize
    return _minimize_bfgs(fun, x0, args, jac, callback, **options)
  File "/usr/lib/python3/dist-packages/scipy/optimize/optimize.py", line 913, in _minimize_bfgs
    gfk = myfprime(x0)
  File "/usr/lib/python3/dist-packages/scipy/optimize/optimize.py", line 292, in function_wrapper
    return function(*(wrapper_args + args))
  File "/usr/lib/python3/dist-packages/scipy/optimize/optimize.py", line 688, in approx_fprime
    return _approx_fprime_helper(xk, f, epsilon, args=args)
  File "/usr/lib/python3/dist-packages/scipy/optimize/optimize.py", line 622, in _approx_fprime_helper
    f0 = f(*((xk,) + args))
  File "/usr/lib/python3/dist-packages/scipy/optimize/optimize.py", line 292, in function_wrapper
    return function(*(wrapper_args + args))
TypeError: <lambda>() missing 1 required positional argument: 'y'

任何人都可以给我一个提示我做错了什么?

4

1 回答 1

1

您的 lambda 需要为x. 我使用它来工作:

>>> lamXY = lambda x: (x[0]-2)**2 + x[1]**2
>>> q0XY = np.ones(2)
>>> solXY = optimize.minimize(lamXY, x0=q0XY)
>>> solXY
      fun: 3.865407235741147e-16
 hess_inv: array([[0.75, 0.25],
       [0.25, 0.75]])
      jac: array([-9.04871520e-09, -1.62848344e-08])
  message: 'Optimization terminated successfully.'
     nfev: 12
      nit: 2
     njev: 3
   status: 0
  success: True
        x: array([ 1.99999999e+00, -1.55929978e-08])

虽然这通常不适用于 python 中的 lambda,但看起来 scipy 期望 lambda 具有单个输入变量。

于 2019-07-18T16:04:37.037 回答