如果您不介意使用其他库,我会推荐 scipy 使用这个库:
from scipy.optimize import minimize
import numpy as np
def OF(x0, v_1, v_2, v_3, v_4):
value_to_minimize = 0.0
for i in range(0, len(v_1)):
value_to_minimize += np.abs(v_1[i] - (v_2[i] * x0[0] + v_3[i] * x0[1] + v_4[i] * x0[2]))
return value_to_minimize
if __name__ == '__main__':
x0 = np.array([0, 0, 0])
v_1 = np.random.randint(10, size = 10000)
v_2 = np.random.randint(10, size = 10000)
v_3 = np.random.randint(10, size = 10000)
v_4 = np.random.randint(10, size = 10000)
minx0 = np.repeat(0, [len(x0)] , axis = 0)
maxx0 = np.repeat(np.inf, [len(x0)] , axis = 0)
bounds = tuple(zip(minx0, maxx0))
cons = {'type':'eq',
'fun':lambda x0: 1 - sum(x0)}
res_cons = minimize(OF, x0, (v_1, v_2, v_3, v_4), bounds = bounds, constraints=cons, method='SLSQP')
print(res_cons)
print('Current value of objective function: ' + str(res_cons['fun']))
print('Current value of controls:')
print(res_cons['x'])
输出是:
fun: 27919.666908810435
jac: array([5092. , 5672. , 5108.39868164])
message: 'Optimization terminated successfully.'
nfev: 126
nit: 21
njev: 21
status: 0
success: True
x: array([0.33333287, 0.33333368, 0.33333345])
Current value of objective function: 27919.666908810435
Current value of controls:
[0.33333287 0.33333368 0.33333345]
但显然这里的实际值意义不大,因为我只是对v_ 值使用了随机整数...只是一个演示,该模型将满足您对c 值加1 和非边界的约束小于零(负)。
编辑更新: 没有仔细研究 OF/约束以意识到这是一个线性问题...应该使用线性求解器算法(不过,您可以使用非线性,它是不过过分了)。
scipy 的线性求解器不适用于像这样的复杂优化问题,回到cvxpy:
import numpy as np
import cvxpy as cp
# Create two scalar optimization variables.
x = cp.Variable()
y = cp.Variable()
z = cp.Variable()
v_1 = np.random.randint(10, size = 10000)
v_2 = np.random.randint(10, size = 10000)
v_3 = np.random.randint(10, size = 10000)
v_4 = np.random.randint(10, size = 10000)
constraints = [x + y + z == 1, x >= 0, y >= 0, z >= 0]
objective = cp.Minimize(cp.sum(cp.abs(v_1 - (v_2 * x + v_3 * y + v_4 * z))))
prob = cp.Problem(objective, constraints)
print("Value of OF:", prob.solve())
print('Current value of controls:')
print(x.value, y.value, z.value)
输出:
Value of OF: 27621.999978414093
Current value of controls:
0.3333333333016109 0.33333333406414983 0.3333333326298208