参考我下面的代码(仅原始代码的相关部分),因为x0是4×3数组,x也应该是相同的。但是我得到了标量变量的无效索引' constraint1中的错误。
我在scipy.optimize.minimize (COBYLA and SLSQP) ignores constraints initiated within for loop
的答案中迭代地编写了约束编写约束的任何更好(通用)方式都会很棒。提前谢谢!
我需要约束循环,因为这只是一个玩具优化问题而不是我希望解决的原始优化问题(博弈论)。
代码(链接到下面的完整代码):
def constraint1(i):
def g(x):
con = 20
for k in range(3):
con = con - x[i][k]
return con
return g
x0 = np.array([[5,5,5],[5,5,5],[5,5,5],[5,5,5]])
cons = []
for i in range(4):
cons.append({'type': 'ineq', 'fun': constraint1(i)})
solution = minimize(objective,x0,method='SLSQP',\
bounds=None,constraints=cons)
错误(请忽略上面的行号是稍微大一点的代码的一部分):
Traceback (most recent call last):
File "opt.py", line 44, in <module>
bounds=None,constraints=cons)
File "C:\Users\dott\Anaconda2\lib\site-packages\scipy\optimize\_minimize.py", line 458, in minimize constraints, callback=callback, **options)
File "C:\Users\dott\Anaconda2\lib\site-packages\scipy\optimize\slsqp.py", line 312, in _minimize_slsqp
mieq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in cons['ineq']]))
File "opt.py", line 15, in g
con = con - x[i][k]
IndexError: invalid index to scalar variable.
答案 0 :(得分:0)
似乎优化任务会使您的初始猜测变平并在每次迭代展平解决方案阵列后返回(而不是4x3阵列,它返回1x12阵列)。这就是你遇到这种错误的原因。您应该将目标和约束函数中的x
数组从1x12重新整形为4x3。之后,您可以访问x
变量的第二维并避免IndexError: invalid index to scalar variable.
。你的功能应该是这样的:
def objective(x):
global q
sum = 0
x = x.reshape((4, 3))
for i in range(4):
for j in range(3):
sum = sum + x[i][j]*q[i][j]
return -1*sum
def constraint1(i):
def g(x):
con = 20
x = x.reshape((4, 3))
for k in range(3):
con = con - x[i][k]
return con
return g
def constraint2(k):
def h(x):
sum_eq = 20
x = x.reshape((4, 3))
for i in range(4):
sum_eq = sum_eq - x[i][k]
return sum_eq
return h