python - 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]
解决方案
要解决此问题,您可以使用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]
推荐阅读
- linux - 如何将命令的输出写入多个文本文件,其中文件名基于部分命令输出?
- javascript - Why do i get different value when i use gmp_init() in PHP , compared with bigint() in Js
- node.js - BlockStatement 预期节点的属性主体 [41] 为 ["Statement"] 类型,但得到了 "AssignmentExpression"
- python - 如何添加到 HTML 元素?
- dolphindb - 如何在函数内部定义共享表?
- angular - 如何在没有分层路由的情况下实现主/细节组件?
- prometheus - 如何在 Grafana 表中显示多个 Prometheus 服务器名称?
- email - 有没有办法将变量设置为 Sieve 中的字符串列表?
- python - Libeosa 在尝试读取音频文件时随机崩溃,尽管它在其他时候可以正常读取相同的文件
- angular - 收到父数据之前的角度子渲染