簡體   English   中英

CVXPY:違反約束

[英]CVXPY: Constraint Violation

我正在嘗試解決 cvxpy 中的優化程序。 問題在於它返回的答案違反了它給出的基本約束。 我之前成功運行過這個程序,並試圖模擬與以前相同的代碼,但這個問題讓我很困惑我哪里出錯了。 任何幫助,將不勝感激。

我正在嘗試解決的優化問題:

對象函數:最大化 0.1a1 + 0.1428a2 + 0.2a3
st 7a1 + 11a2 + 16a3 <= 80
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.]]

你的尺寸壞了。

矩陣乘法:

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)

您可能想將列向量a 更改為行向量a。 這也意味着 w (以及我不會觸及的其他表達式)的轉置

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM