我正在尝试最小化方程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/