首页 > 解决方案 > Scipy 优化最小化 - 将变量范围限制为 0 或 1

问题描述

我试图最小化方程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]

标签: pythonscipy-optimize

解决方案


要解决此问题,您可以使用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]

推荐阅读