python - 设置x0 scipy python的特定数组子集的边界
问题描述
我需要在 scipy.optimize.minimize() 函数中为 x0 数组的每个子集设置不同的界限。
这是我到目前为止所尝试的:
x0 = np.zeros(20)
# disp = x0[0:5]
# w = x0[5:10]
# qi = x0[10:15]
# qai = x0[15:20]
#bonds
bnds = (((-np.inf, np.inf) for i in x0[0:5]), ((0, 1) for i in x0[5:10]), ((0, np.inf) for i in x0[10:15]), ((int(-1000000), int(100000000)) for i in x0[15:20]))
cons = [{'type': 'ineq', 'fun': lambda x: x[10:15] - lotMin * x[5:10]},
{'type': 'eq', 'fun': lambda x: x[15:20] - x[10:15] / arrot},
{'type': 'ineq', 'fun': lambda x: x[0:5]},
{'type': 'ineq', 'fun': lambda x: x[15:20] - D},
{'type': 'ineq', 'fun': lambda x: -(x[10:15] - M * x[5:10])},
{'type': 'ineq', 'fun': lambda x: x[10:15] - x[5:10]},
{'type': 'eq', 'fun': lambda x: x[0:5] - Disp_0 - x[10:15] + D}]
res = minimize(fun=lambda x: sum(x[0:4]*ho)+co*sum(x[5:9]), constraints=cons, x0=x0, bounds=bnds,
method='SLSQP', options=dict(ftol=1e-6))
这是我得到的错误:
Traceback (most recent call last):
File "C:\Users\davide.tamagnini.con\AppData\Roaming\JetBrains\PyCharmCE2021.1\scratches\scratch_1.py", line 84, in <module>
res = minimize(fun=lambda x: sum(x[0:4]*ho)+co*sum(x[5:9]), constraints=cons, x0=x0, bounds=bnds,
File "C:\Python\Python395\lib\site-packages\scipy\optimize\_minimize.py", line 627, in minimize
return _minimize_slsqp(fun, x0, args, jac, bounds,
File "C:\Python\Python395\lib\site-packages\scipy\optimize\slsqp.py", line 259, in _minimize_slsqp
new_bounds = old_bound_to_new(bounds)
File "C:\Python\Python395\lib\site-packages\scipy\optimize\_constraints.py", line 323, in old_bound_to_new
lb, ub = zip(*bounds)
ValueError: too many values to unpack (expected 2)
有没有人遇到同样的问题?
在此先感谢,戴维德
解决方案
正如评论中已经提到的,bounds
需要是一个元组序列。因此,您可以执行以下操作:
# Bounds
bnds = []
for i, _ in enumerate(x0):
if i <= 4:
bnds.append((-np.inf, np.inf))
elif 5 <= i <= 9:
bnds.append((0, np.inf))
else:
bnds.append(-1000000, 100000000)
推荐阅读
- android - 如何让android应用跳过很多帧?
- workflow - 如何使用 GitHub 操作跳过矩阵配置?
- python - Pandas 按列对索引(5 元组)
- javascript - react native:有没有办法用相同的逻辑将 Picker 更改为 TextInput?
- python - 如何在python中的所有列和行中复制公式
- python - 在 Django - Django 中更新外键对象时如何保持字段值不变?
- google-analytics - 在 gtag.js 中设置 setSiteSpeedSampleRate
- api - Oanda API - 发行价格 - 工具
- javascript - 如何更新惯性js和vue中的属性
- flutter - 将 Flutter 网站部署到服务器时出现问题