python - 为什么 scipy.minimize 忽略我的约束?

标签 python numpy scipy

我有一个受限优化问题,正在尝试使用 scipy.optimize.minimize 来解决。

基本上,我将一个参数 f 拟合到具有约束的 ODE 系统: f>0 和

f*1000< 500

我在下面写了一篇 MWE。在这个简单的情况下,很明显 0<f<0.5,但在我的实际问题中,先验上限并不明显,因此存在不等式约束。

from __future__ import division
import numpy as np
from scipy.integrate import odeint
from scipy.optimize import minimize

def myeqs(y,t,beta, gamma,N):
    dy0 = -(beta/N)*y[0]*y[1]
    dy1 = (beta/N)*y[0]*y[1] - gamma*y[1]
    dy2 = gamma*y[1]

    return [dy0,dy1,dy2]

def runModel(f, extraParams):
    [beta, gamma, N, initCond, time]= extraParams
    S0 = (1-f)*initCond[0]
    I0 = initCond[1]
    R0 = f*initCond[0]
    tspan = np.linspace(time[0], time[1], int(time[1] - time[0]))
    sol = odeint(myeqs, [S0,I0,R0], tspan, args=(beta, gamma, N))
    return sol

y0 = [1000, 1, 0]
extraParams = [0.5, 0.25, 1000, y0, [0,150]]


def computeSimple(f, extraParams):
   sol = runModel(f, extraParams)
   return np.abs((sol[-1,2] - sol[0,2]))


def c1(f):
    return f*1000.0 - 500.0


cons = ({'type': 'ineq', 'fun': c1})

#cons = ({'type': 'ineq',
 #  'fun': lambda x: x[0]*1000 - 500}, )

res = minimize(computeSimple, 0.2, args=(extraParams, ), method='SLSQP',       bounds=((0,1.5), ), constraints=cons)
print res.x

print c1(res.x)

如果您运行此命令,您将看到 res.x 始终是边界的上限,无论约束如何... 我的错误在哪里? 提前致谢

最佳答案

你的约束条件倒退了。这个约束:

def c1(f):
    return f*1000.0 - 500.0

f 限制为至少 0.5,而不是最多 0.5

关于python - 为什么 scipy.minimize 忽略我的约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40753159/

相关文章:

python - 将 Numpy 数组 reshape 为多维数组

python - 将列表元素与元组元素合并

python 稀疏 csr 矩阵 : how to serialize it

python - 传入 Flask 的可能路径列表?

python - NumPy 中的 SQL join 或 R 的 merge() 函数?

Python设置不存在的数组的值默认为0

numpy - 使用 np.einsum 和 np.tensordot 执行四阶张量的坐标变换

scipy - 有没有办法将 scipy.optimize.fsolve 与 jit_integrand_function 和 scipy.integrate.quad 一起使用?

python - Scipy mmread 用于矩阵数组实数通用

python - Pandas 数据框获取每组的第一行并复制到其他行