python fmin_slsqp - 约束错误

python fmin_slsqp - error with constraints

我正在练习 SciPy,但在尝试使用 fmin_slsqp 时遇到错误。我设置了一个问题,我想在给定一组约束的情况下最大化 objective 函数 U。

我有两个控制变量,x[0,t] 和 x[1,t],如您所见,它们由 t(时间段)索引。 objective函数是:

def obj_fct(x, alpha,beta,Al):
U = 0
x[1,0] = x0
for t in trange:
    U = U - beta**t * ( (Al[t]*L)**(1-alpha) * x[1,t]**alpha - x[0,t])
return U

约束是针对这两个变量定义的,其中一个将变量从一个时期 (t) 链接到另一个时期 (t-1)。

def constr(x,alpha,beta,Al):
return np.array([
    x[0,t],
    x[1,0] - x0,
    x[1,t] - x[0,t] - (1-delta)*x[1,t-1]
    ])

最后这里是fmin_slsqp的用法:

sol = fmin_slsqp(obj_fct, x_init, f_eqcons=constr, args=(alpha,beta,Al))

撇开有更好的方法来解决此类动态问题这一事实不谈,我的问题是关于语法的。当 运行 这个简单的代码时,我得到以下错误:

    Traceback (most recent call last):
  File "xxx", line 34, in <module>
    sol = fmin_slsqp(obj_fct, x_init, f_eqcons=constr, args=(alpha,beta,Al))
  File "D:\Anaconda3\lib\site-packages\scipy\optimize\slsqp.py", line 207, in fmin_slsqp
    constraints=cons, **opts)
  File "D:\Anaconda3\lib\site-packages\scipy\optimize\slsqp.py", line 311, in _minimize_slsqp
    meq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in cons['eq']]))
  File "D:\Anaconda3\lib\site-packages\scipy\optimize\slsqp.py", line 311, in <listcomp>
    meq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in cons['eq']]))
  File "xxx", line 30, in constr
    x[0,t],
IndexError: too many indices for array
[Finished in 0.3s with exit code 1]

我做错了什么?

代码的初始部分,为参数赋值,是:

   from scipy.optimize import fmin_slsqp
import numpy as np

T = 30
beta = 0.96
L = 1
x0 = 1
gl = 0.02
alpha = 0.3
delta = 0.05
x_init = np.array([1,0.1])

A_l0 = 1000
Al = np.zeros((T+1,1))
Al[1] = A_l0

trange = np.arange(1,T+1,1, dtype='Int8') # does not include period zero
for t in trange: Al[t] = A_l0*(1 + gl)**(t-1) 

传递给您的 objective 和约束函数的数组 x 将是一个 一维 数组(就像您的 x_init 是).您不能为具有两个索引的一维数组建立索引,因此 x[1,0]x[0,t] 等表达式将产生错误。