【问题标题】:CVXPY: Constraint ViolationCVXPY:违反约束
【发布时间】:2021-10-25 17:35:08
【问题描述】:

我正在尝试解决 cvxpy 中的优化程序。问题是它返回的答案违反了给出的基本约束。我之前成功地运行过这个程序,并尝试模拟与以前相同的代码,但这个问题让我很困惑我哪里出错了。任何帮助将不胜感激。

我正在尝试解决的优化问题:

obj 函数:最大化 0.1a1 + 0.1428a2 + 0.2a3
s.t 7a1 + 11a2 + 16a3 a1, a2, a3 > =0, 所有整数

当我运行下面的代码时,它给我的 a1、a2 和 a3 的值为 5,这违反了给定的约束。

import cvxpy as cvx
import numpy as np
import scipy as sc
from scipy import linalg

#Define Starting Matrix
A1 = np.array([10,0,0])
A2 = np.array([0,7,0])
A3 = np.array([0,0,5])

#Optimal Basis and Inverse
B = np.array([A1, A2, A3])
print(f"B:{B}")
Binv = linalg.inv(B)
print(f"B-1:{Binv}")

#Define Cost Matrix
c = np.array([1, 1, 1])

#Optimal Dual Solution, y.hat
yhat = np.matmul(c,Binv)
print(f"y.hat:{yhat}")

#Pricing Problem
a = cvx.Variable(shape=(3,1), name="a")
w = np.array([[7,11,16]])

#Define Obj Function
objective2 = cvx.Maximize(cvx.matmul(yhat,a))

#Define Constraints
constraint2 = [
    cvx.matmul(a,w)<=80,
    a >=0
]

#Define Problem and Solve
knapsack = cvx.Problem(objective2, constraint2)
solution2 = knapsack.solve()
print(solution2)
print(a.value)

2.2142857137502494    
[[5.]    
 [5.]    
 [5.]]

【问题讨论】:

  • 我在你的代码中没有看到integer

标签: python numpy mathematical-optimization cvxpy integer-programming


【解决方案1】:

您的尺寸已损坏。

矩阵乘法:

a = cvx.Variable(shape=(3,1), name="a")  # 3 x 1
w = np.array([[7,11,16]])                # 1 x 3

结果:

z = a * w      # 3 x 3

您可以轻松验证这一点:

print(cvx.matmul(a,w).shape)
# (3, 3)

您可能希望将 column-vector a 更改为 row-vector a。这也意味着 w 的 transpose (以及我不会触及的其他表达式):

a = cvx.Variable(shape=(1,3), name="a")
w = np.array([7,11,16]]).transpose()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-10
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    相关资源
    最近更新 更多