python - Scipy 优化最小化 - 将变量范围限制为 0 或 1

标签 python scipy-optimize

我正在尝试最小化方程x[0]+x[1]+x[2]+x[3]

假设 A = [5,3,8,6]

约束方程为A1 x[0] + A2 x[1] + A3 x[2] + A4 x[3] = 11,其中 0 <= x <= 1 且 x 应为整数(0 或 1)。

x 的预期输出为 [0,1,1,0]

请帮助我实现这一目标。

请在下面找到我尝试过的代码。

代码:

from scipy.optimize import minimize

#objective function definition
def objective(x):
    return x[0]+x[1]+x[2]+x[3]

#constraint definition
def constraint1(x):
    sum_eq = 11
    a = [5,3,8,6]
    for i in range(len(a)):
        sum_eq = sum_eq - (a[i]*x[i])
    return sum_eq

#set the bounds
b = (0,1)
bnds = (b,b,b,b)
cons1 = {'type':'eq','fun':constraint1}

#initialisation
x0 = [0,0,0,1]

sol = minimize(objective,x0,method='SLSQP',bounds=bnds, constraints=cons1)
print(sol.x)

输出:

[3.53445929e-16 3.83487389e-17 1.00000000e+00 5.00000000e-01]

最佳答案

要解决这个问题,您可以使用 fmin_slsqp 。首先,您需要定义将从方程中返回 0 的函数。然后使用参数评估函数以找到具有声明边界的解决方案。

from scipy.optimize import fmin_slsqp
import numpy as np


def zero_equation(x):
    return (x*np.array([5,3,8,6])).sum()-11


def function(x):
    return x[0]+x[1]+x[2]+x[3]


b = (0,1)
bounds = (b,b,b,b)
starting_parameters = np.array([0,0,0,1])
result = fmin_slsqp(function, x0=starting_parameters , bounds=bounds ,eqcons=[zero_equation])

输出:

[0.  0.  1.  0.5]

关于python - Scipy 优化最小化 - 将变量范围限制为 0 或 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60109268/

相关文章:

python - 在 Docker 镜像中克隆 git 存储库失败

python - 快速问题 : Use the default value of the scipy. optimize.minimize tol 参数

python - TypeError : Improper input: N=3 must not exceed M=1, 不确定我的尺寸有什么问题?

python - 如何在 scipy.optimize.minimize 上为 Powell 方法设置正确的方向向量?

python - 代码优化: How to optimize a code using scipy minimize?

python - GAE : how can I combine a BlobstoreUploadHandler and a RequestHandler in 1 webpage

python - 如何在keras中连接两层?

python - 通过 SSH 连接到 EBS 创建的 EC2 实例

python - Python 包名可以以数字开头吗?